本文介绍了为什么 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):

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

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

08-14 19:31
查看更多