将派生类集合分配给基类集合编译错误

时间:2011-06-08 12:49:43

标签: c# generics inheritance

我有两个班级

class Base
{

}
class Derived : Base
{

}

Base base = new Derived();没有编译错误

如果我ICollection<Base> collBase = new List<Derived>();,则会出现编译错误。还有其他方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:4)

如果您使用的是.Net版本4:将ICollection更改为IEnumerable

http://msdn.microsoft.com/en-us/library/dd799517.aspx

编辑 - 更有用的阅读

http://blogs.msdn.com/b/ericlippert/archive/2007/10/26/covariance-and-contravariance-in-c-part-five-interface-variance.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!