How to make a generic class with inheritance?

后端 未结 2 1273
甜味超标
甜味超标 2020-12-20 08:26

How can I make the following code work? I don\'t think I quite understand C# generics. Perhaps, someone can point me in the right direction.

    public abs         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-20 08:59

    The reason this does not work is because it cannot be determined to be safe. Suppose you have

    List giraffes = new List();
    List animals = giraffes; // suppose this were legal.
    // animals is now a reference to a list of giraffes, 
    // but the type system doesn't know that.
    // You can put a turtle into a list of animals...
    animals.Add(new Turtle());  
    

    And hey, you just put a turtle into a list of giraffes, and the type system integrity has now been violated. That's why this is illegal.

    The key here is that "animals" and "giraffes" refer to the SAME OBJECT, and that object is a list of giraffes. But a list of giraffes cannot do as much as a list of animals can do; in particular, it cannot contain a turtle.

提交回复
热议问题