C# Generics and polymorphism: an oxymoron?

前端 未结 6 1624
日久生厌
日久生厌 2020-12-16 12:17

I just want to confirm what I\'ve understood about Generics in C#. This has come up in a couple code bases I\'ve worked in where a generic base class is used to create type

6条回答
  •  清酒与你
    2020-12-16 12:43

    It seems that once you introduce a Generic into an inheritance hierarchy or interface, you can no longer use that family of classes in a polymorphic way

    Correct, it's quite similar to this situation:

    class StringContainer
    {
    }
    
    class IntContainer
    {
    }
    
    StringContainer container = new IntContainer(); // fails to compile
    

    but you could do this:

    class Container
    {
    }
    
    class Container : Container
    {
    }
    
    Container container = new Container(); // OK
    

提交回复
热议问题