什么时候适合使用泛型对战继承? [英] When is it Appropriate to use Generics Versus Inheritance?

查看:480
本文介绍了什么时候适合使用泛型对战继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么情况下使用泛型了继承,反之亦然自己的相关利益,以及他们应该如何最好地结合起来?

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

感谢您的回答家伙。

我要去尝试陈述的动机这个问题,尽我所能: 我有一个类,如下所示:

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>) { ... }
}

现在假设我有一个资料库需要一个InformationReturn的说法,是要strore不同领域的数据库取决于信息的对象T的类型。它是最好创建不同的存储库为每个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?

注意:其他客户端code必须的运作方式不同基于T,以及类型

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

推荐答案

他们真的不同的想法完全。泛型允许你申报常见的特殊功能(在冠冕堂皇的自相矛盾的风险),在一般的方式。 A 名单,其中,INT&GT; 不起作用任何不同于一个名单,其中,串&GT; ,除了数据的类型这是内举行。

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<int> doesn't function any differently from a List<string>, aside from the type of data that is held inside.

尽管继承可以用来做同样的事情,我可以创建一个列表类,那么 IntList 的StringList 类继承它。我可以很容易地使这两个类的功能完全不同的,或者在另一个没有可用的一个报价的功能。

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.

修改

审核编辑的问题后,回答sortof是看情况。你可以争论的双方 - 事实上,LINQ to SQL和实体框架是两个反射检查使用仿制药,并强类型实体类和其他存储库类两者的组合。你当然可以把你正在查看的方式,只知道,在一般情况下,是可以解决的或者与反射或别的东西很可能会在被解决了快一个问题,别的东西。归结到一点,你如何权衡很想之间的性能,可维护性,可读性和可靠性。

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.

这篇关于什么时候适合使用泛型对战继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆