为什么IEnumerable的&LT; T&GT;自IEnumerable继承? [英] Why does IEnumerable<T> inherit from IEnumerable?
问题描述
这可能是一个老问题:为什么的IEnumerable&LT; T&GT;
从的IEnumerable继承
This might be a old question: Why does IEnumerable<T>
inherit from IEnumerable
?
这是.NET怎么做,但它带来了一点小麻烦。每次我写一个类实现 IEumerable&LT; T&GT;
,我必须写两个的GetEnumerator()
功能,一个用于的IEnumerable&LT; T&GT;
,另一个的IEnumerable
This is how .NET do, but it brings a little trouble. Every time I write a class implements IEumerable<T>
, I have to write two GetEnumerator()
functions, one for IEnumerable<T>
and the other for IEnumerable
.
和的IList&LT; T&GT;
不自IList继承。
And, IList<T>
doesn't inherit from IList.
我不知道为什么的IEnumerable&LT; T&GT;
的设计在其他的方式
I don't know why IEnumerable<T>
is designed in other way.
推荐答案
直起马的嘴(Hejlsberg为):
Straight from the horse's mouth (Hejlsberg):
在理想情况下所有的泛型集合接口(如的ICollection&LT; T&GT;
,的IList&LT; T&GT;
)将继承从他们非一般的同行,使得通用接口的实例可以与通用和非通用code均可使用。例如,这将是方便,如果一个的IList&LT; T&GT;
可以传递到code,它期望一个的IList
。
Ideally all of the generic collection interfaces (e.g.
ICollection<T>
,IList<T>
) would inherit from their non-generic counterparts such that generic interface instances could be used both with generic and non-generic code. For example, it would be convenient if anIList<T>
could be passed to code that expects anIList
.
事实证明,唯一的通用接口,也是它可能是的IEnumerable&LT; T&GT;
,因为只有的IEnumerable&LT; T&GT;
是禁忌变:在的IEnumerable&LT; T&GT;
,类型参数T只用在输出位置(返回值),而不是在输入位置(参数)。 的ICollection&LT; T&GT;
和的IList&LT; T&GT;
使用T IN输入和输出位置,并且这些接口,因此不变。 (顺便说一句,他们将被潮水变如果T仅在输入位置使用的,但是这并不重要在这里。)
As it turns out, the only generic interface for which this is possible is IEnumerable<T>
, because only IEnumerable<T>
is contra-variant: In IEnumerable<T>
, the type parameter T is used only in "output" positions (return values) and not in "input" positions (parameters). ICollection<T>
and IList<T>
use T in both input and output positions, and those interfaces are therefore invariant. (As an aside, they would have been contra-variant if T was used only in input positions, but that doesn't really matter here.)
&LT; ...略...>
<...snip...>
因此,要回答你的问题,的IEnumerable&LT; T&GT;
从继承了IEnumerable
,因为它可以! : - )
So, to answer your question, IEnumerable<T>
inherits from IEnumerable
because it can! :-)
这篇关于为什么IEnumerable的&LT; T&GT;自IEnumerable继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!