When is it Appropriate to use Generics Versus Inheritance?

前端 未结 7 716
傲寒
傲寒 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 00:45

    They're really different ideas altogether. Generics allow you to declare common "specific" functionality (at the risk of sounding oxymoronic) in a general way. A List doesn't function any differently from a List, aside from the type of data that is held inside.

    While inheritance could be used to do the same thing, I could create a List class, then an IntList and a StringList class that inherit from it. I could easily make these two classes function entirely differently, or have one offer functionality not available in the other one.

    Edit

    After reviewing the edit to the question, the answer sortof is "it depends." You can make arguments for both sides--and, indeed, LINQ to SQL and the Entity Framework are both a combination of both reflective inspection using generics, and strongly-typed entity classes and other repository classes. You can certainly take the approach that you're looking at, just know that, in general, a problem that can be solved either with reflection or with something else is LIKELY going to be faster when solved by the "something else." It comes down to how much of a tradeoff you want among performance, maintainability, readability, and reliability.

提交回复
热议问题