Distinction between iterator and enumerator

后端 未结 9 631
南旧
南旧 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 09:02

    "Whereas a foreach statement is the consumer of the enumerator, an iterator is the producer of the enumerator."

    The above is how "C# 5.0 In A NutShell" explains it, and has been helpful for me.

    In other words, the foreach statement uses MoveNext(), and the Current property of the IEnumerator to iterate through a sequence, while the iterator is used to produce the implementation of the IEnumerator that will be used by the foreach statement. In C#, when you write an iterator method containing a yield statement, the compiler will generate a private enumerator for you. And when you iterate through the items in the sequence, it will call the MoveNext() and Current property of the private enumerator. These methods/properties are implemented by your code in the iterator method that will be called repeately to yield values until there are not values left to yield.

    This is my understanding of how C# define enumerators, and iterators.

提交回复
热议问题