为什么 IEnumerable<T>从 IEnumerable 继承? [英] Why does IEnumerable&lt;T&gt; inherit from IEnumerable?

查看:31
本文介绍了为什么 IEnumerable<T>从 IEnumerable 继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是个老问题:为什么 IEnumerable 继承自 IEnumerable?

.NET 就是这样做的,但它带来了一些麻烦.每次写一个类实现IEumerable,都要写两个GetEnumerator()函数,一个用于IEnumerable和另一个用于 IEnumerable.

而且,IList 不继承自 IList.

我不知道为什么 IEnumerable 以其他方式设计.

解决方案

直接来自马口 (Hejlsberg):

<块引用>

理想情况下,所有泛型集合接口(例如 ICollectionIList)都将从它们的非泛型对应物继承,以便泛型接口实例可以可用于泛型和非泛型代码.例如,如果可以将 IList 传递给需要 IList 的代码会很方便.

<块引用>

事实证明,唯一可能的通用接口是 IEnumerable,因为只有 IEnumerable 是逆变的:在 IEnumerable,类型参数T只在输出"中使用位置(返回值)而不是输入"位置(参数).ICollectionIList 在输入和输出位置都使用 T,因此这些接口是不变的.(顺便说一句,如果 T 仅用于输入位置,它们将是逆变的,但这在这里并不重要.)

<块引用>

<...剪断...>

所以,为了回答你的问题,IEnumerable 继承自 IEnumerable 因为它可以!:-)

This might be a old question: Why does IEnumerable<T> inherit from 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.

And, IList<T> doesn't inherit from IList.

I don't know why IEnumerable<T> is designed in other way.

解决方案

Straight from the horse's mouth (Hejlsberg):

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 an IList<T> could be passed to code that expects an IList.

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

<...snip...>

So, to answer your question, IEnumerable<T> inherits from IEnumerable because it can! :-)

这篇关于为什么 IEnumerable<T>从 IEnumerable 继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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