[英]Why is IEnumerable<T> necessary when there is IEnumerator<T>?
Disclaimer: I understand the difference between IEnumerable<T>
and IEnumerator<T>
and how to use both. 免责声明:我理解
IEnumerable<T>
和IEnumerator<T>
之间的区别以及如何使用它们。 This is not a duplicate of this or this . 这与此或此不重复。
This is more of a design question - since IEnumerator<T>
already encapsulates all the necessary information ( .Current
, .MoveNext()
) about something that can be enumerated, then what's the point of introducing a type ( IEnumerable<T>
) whose sole purpose is to return an instance of the former? 这更像是一个设计问题 - 因为
IEnumerator<T>
已经封装了可以枚举的所有必要信息( .Current
, .MoveNext()
),那么引入一个类型( IEnumerable<T>
)的重点是什么呢?唯一的目的是返回前者的实例?
To be specific: 再具体一点:
Why can't foreach
be designed to iterate directly through an IEnumerator<T>
, like so: 为什么不能将
foreach
设计为直接通过IEnumerator<T>
进行迭代,如下所示:
// foreach (var e in anEnumerator) { //... } while (anEnumerator.MoveNext()) { doSomething(anEnumerator.Current); }
Why can't Linq be built based directly off of IEnumerator<T>
? 为什么Linq不能直接基于
IEnumerator<T>
构建?
The two interfaces each represent very different concepts. 这两个接口各自代表非常不同的概念。
IEnumerable<T>
is something that "allows enumeration", where IEnumerator<T>
is the representation of the enumeration itself. IEnumerable<T>
是“允许枚举”的东西,其中IEnumerator<T>
是枚举本身的表示。
If you were to merge these together, it would be impossible to enumerate a single collection more than once at the same time (without some other mechanism in place). 如果要将这些合并在一起,则不可能同时枚举单个集合(没有其他一些机制)。 For example, two threads doing a
foreach
over an array would no longer work, where that is perfectly acceptable in the current design. 例如,在数组上执行
foreach
两个线程将不再起作用,这在当前设计中是完全可接受的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.