Assign Derived Class Collection to Base Class Collection compilation error

后端 未结 1 430
忘掉有多难
忘掉有多难 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 dogs = new List(); //error (Or List, same error) because...
    dogs.Add(new cat()); //you just dogged a cat
    
    IEnumerable dogs = new List(); // this is ok!
    

    0 讨论(0)
提交回复
热议问题