Distinction between iterator and enumerator

后端 未结 9 625
南旧
南旧 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:06

    What C# calls an iterator is more commonly (outside of the C# world) called a generator or generator function (e.g. in Python). A generator function is a specialized case of coroutine. A C# iterator (generator) is a special form of an enumerator (a data type implementing the IEnumerable interface).

    I dislike this usage of the term iterator for a C# generator because it is just as much an enumerator as it is an iterator. Too late for Microsoft to change its mind though.

    For contrast consider that in C++ an iterator is a value which is used primarily to access sequential elements in a collection. It can be advanced, derferenced to retrieve a value, and tested to see whether the end of the collection has been reached.

提交回复
热议问题