Distinction between iterator and enumerator

后端 未结 9 624
南旧
南旧 2020-12-07 08:47

An interview question for a .NET 3.5 job is \"What is the difference between an iterator and an enumerator\"?

This is a core distinction to make, what with LINQ, etc

9条回答
  •  执念已碎
    2020-12-07 08:58

    In C# 2+, iterators are a way for the compiler to automatically generate the IEnumerable and/or IEnumerable interfaces for you.

    Without iterators, you would need to create a class implementing IEnumerator, including Current, MoveNext, and Reset. This requires a fair amount of work. Normally, you would create a private class that implemtented IEnumerator for your type, then yourClass.GetEnumerator() would construct that private class, and return it.

    Iterators are a way for the compiler to automatically generate this for you, using a simple syntax (yield). This lets you implement GetEnumerator() directly in your class, without a second class (The IEnumerator) being specified by you. The construction of that class, with all of its members, is done for you.

    Iterators are very developer friendly - things are done in a very efficient way, with much less effort.

    When you use foreach, the two will behave identically (provided you write your custom IEnumerator correctly). Iterators just make life much simpler.

提交回复
热议问题