When is it Appropriate to use Generics Versus Inheritance?

前端 未结 7 705
傲寒
傲寒 2020-12-16 00:12

What are the situations and their associated benefits of using Generics over Inheritance and vice-versa, and how should they be best combined?

Thanks for the answer

7条回答
  •  伪装坚强ぢ
    2020-12-16 01:02

    Generics and inheritance are two separate things. Inheritance is an OOP concept and generics are a CLR feature that allows you specify type parameters at compile-time for types that expose them.

    Inheritance and generics actually work quite well together.

    Inheritance:

    Inheritance allows me to create one type:

    class Pen { }
    

    and then later create another type that extends Pen:

    class FountainPen : Pen { }
    

    This is helpful because I can reuse all the state and behavior of the base class and expose any new behavior or state in FountainPen. Inheritance allows me to rapidly create a more specific version of an existing type.

    Generics:

    Generics are a CLR feature that let me create a type like this:

    class Foo 
    {
        public T Bar { get; set; }
    }
    

    Now when I use Foo I can specify what the type of T will be by providing a generic type argument:

    Foo foo = new Foo();
    

    Now, since I have specified that T shall be an int for the object I have just created, the type of Foo.Bar will also be int since it was declared of type T.

提交回复
热议问题