Assign Derived Class Collection to Base Class Collection compilation error
I have two classes
class Base
{
}
class Derived : Base
{
}
Base base = new Derived()开发者_开发技巧;
no compilation error
if I do ICollection<Base> collBase = new List<Derived>();
it gives the compilation error. Is there any other alternatives to solve this?
If you are using .Net version 4 : Change ICollection to IEnumerable
http://msdn.microsoft.com/en-us/library/dd799517.aspx
Edit - more useful reading
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
attempting to clarify further why you can't do this:
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!
精彩评论