我有两个类(class)
class Base
{
}
class Derived : Base
{
}
Base base = new Derived();没有编译错误
如果我这样做 ICollection<Base> collBase = new List<Derived>();它给出了编译错误。有没有其他方法可以解决这个问题?
请您参考如下方法:
如果您使用的是 .Net 版本 4:将 ICollection 更改为 IEnumerable
http://msdn.microsoft.com/en-us/library/dd799517.aspx
编辑 - 更有用的读物
http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/default.aspx
试图进一步澄清为什么你不能这样做:
class animal {}
class dog : animal {}
class cat : animal {}
ICollection<animal> dogs = new List<dog>(); //error (Or List<T>, same error) because...
dogs.Add(new cat()); //you just dogged a cat
IEnumerable<animal> dogs = new List<dog>(); // this is ok!
