为什么我不能将List<T>
分配给ICollection<I>
,其中T实现接口I?
例如:
public interface IObject {}
public class MyObject : IObject {}
public class Stuff
{
ICollection<IObject> Objects {get;set;}
public Stuff()
{
Objects = new List<MyObject>(); //<-- Cannot implicitly convert type 'ICollection<IObject>' to 'List<MyObject>'. An explicit cast exists.
}
}
我意识到这个错误的解决方案如下:
Objects = (ICollection<IObject>)new List<MyObject>();
或
Objects = new List<IObject>();
但我很好奇为什么。