我有两个类分配派生类集合基类集合编译错误
class Base
{
}
class Derived : Base
{
}
Base base = new Derived();
没有编译错误
如果我做ICollection<Base> collBase = new List<Derived>();
它给人的编译错误。有没有其他办法可以解决这个问题?
我有两个类分配派生类集合基类集合编译错误
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!
说的对! @asawyer – 2011-06-08 12:53:52
来吧...'System.Collection.Generic.List
@Andreas ICollection不是协变安全的,IEnumerable是因为你不能添加到集合中。看看Eric Lipperts撰写的一些关于这个问题的文章,他解释得更好,然后我可以做得更好。 – asawyer 2011-06-08 13:02:17
[一些阅读](http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx)约协方差和反方差会有所帮助。 – 2011-06-08 12:55:23
你正在使用哪种框架?如果你正在使用<4,你可能看看http://stackoverflow.com/questions/833447/why-is-this-cast-not-possible – 2011-06-08 12:55:31
如果有人然后做'collBase',你会发生什么? .Add(new Derived2())',其中'Derived2'是另一个派生自'Base'的类?如果你只想从'collBase'中读*,你可以做@asawyer建议的。如果没有,你需要再想一些。 – AakashM 2011-06-08 12:56:17