Disclaimer: I understand the difference between IEnumerable<T>
and IEnumerator<T>
and how to use both. 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?
To be specific:
Why can't foreach
be designed to iterate directly through an IEnumerator<T>
, like so:
// foreach (var e in anEnumerator) { //... } while (anEnumerator.MoveNext()) { doSomething(anEnumerator.Current); }
Why can't Linq be built based directly off of 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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.