为什么不总是使用泛型? [英] Why not always use Generics?

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

问题描述

我读现有员额仿制药的SO。如果泛型有这么多的优点一样的类型安全,装箱/拆箱没有开销,它的速度很快,为什么不一直使用它?为什么你会永远使用非通用对象呢?

I am reading existing posts on Generics at SO. If Generics has so many advantages like Type safety, no overhead of boxing/unboxing and it is fast, why not always use it? Why would you ever use a non-generic object instead?

编辑(下面的问题进一步扩大)

我有点糊涂了。我最后一次读到泛型,几个月前,我读,如果键入的参数是可变的,一般应采用以prevent错误。我现在似乎可以读,虽然是仿制药的限制执行一个固定的类型,而一个非通用对象可以在运行时定义的参数类型。

I am a bit confused. The last time I read about Generics, a few months ago, I read that if the Type in the parameters is variable, Generic should be used in order to prevent errors. What I seem to be reading now, though, is that Generics limit implementation to a fixed Type, while a non-generic object allows you to define parameter types at run-time.

请帮我看看,我缺少的是什么?

Please help me see what I'm missing?

其次,使用这类结构的适当的面向对象设计(仿制药等)是有益的,当你工作在一个团队中,你的code是可共享的。对于一个孤独的程序员,但规模较小,谁知道是什么类型都有进来的参数,好像没有必要担心,并使用通用或非通用型相差不大。这是准确的?

Secondly, using these kinds of constructs in proper OOP designs (Generics, etc.) are helpful when you are working in a team and your code is shareable. For a lone programmer with a small scale, who knows what Type has to come in the parameter, it seems like there is no need to worry, and little difference between using a Generic or Non-Generic type. Is this accurate?

推荐答案

在一般你的应该的 - 但是,也有当它是不可能的(尤其是当编写库code)时间(不然肯定不方便),了解呼叫类型(甚至在 T )的条款,使非通用类(主要是接口,如的IList 的IEnumerable )是非常有用的。数据绑定就是一个很好的例子。事实上,什么的涉及反射一般是由更难使用仿制药,并且因为(通过反射的性质),你已经的丢失的这些好处,你不妨只是下降到非通用code。反思与仿制药都不是很要好的朋友的所有的。

In general you should - however, there are times (especially when writing library code) when it is not possible (or certainly not convenient) to know about the calling type (even in terms of T), so non-generic types (mainly interfaces such as IList, IEnumerable) are very useful. Data-binding is a good example of this. Indeed, anything that involves reflection is generally made much harder by using generics, and since (via the nature of reflection) you've already lost those benefits, you may as well just drop to non-generic code. Reflection and generics are not very good friends at all.

这篇关于为什么不总是使用泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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