Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 guys.

I'm going to try to state the motivation for this question as best I can: I have a class as shown below:

class InformationReturn<T> where T : Info
{
    InformationReturn(Employee employee, List<T>) { ... }
}

Now suppose I have a repository that takes an InformationReturn argument, that has to strore different fields in a DB depending on the type of Info object T is. Is it better to create different repositories each for the type T is; one repository that uses reflection to determine the type; or is there a better way using inheritance capabilities over/with generics?

Note: other client code must operate differently based on the type of T as well.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
192 views
Welcome To Ask or Share your Answers For Others

1 Answer

You should use generics when you want only the same functionality applied to various types (Add, Remove, Count) and it will be implemented the same way. Inheritance is when you need the same functionality (GetResponse) but want it to be implemented different ways.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...