Assign Derived Class Collection to Base Class Collection compilation error

后端 未结 1 429
忘掉有多难
忘掉有多难 2021-01-16 09:58

I have two classes

class Base
{

}
class Derived : Base
{

}

Base base = new Derived(); no compilation error

if I do <

相关标签:
1条回答
  • 2021-01-16 10:41

    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!
    
    0 讨论(0)
提交回复
热议问题