What is the name of the “yield return” concept? IEnumerable, Iterator, Generator?

自作多情 提交于 2019-12-11 06:56:18

问题


What exactly is the official name of the yield return concept?

public IEnumerable<T> Bar() {
    ...
    yield return foo;
    ...
}

I've heard(read) it being referred to as:

  • Iterator
  • IEnumerabe
  • Generator
  • <your choice>

Isn't an iterator just some "thing" that iterates over something? A List<T> is an IEnumerable<T>, so doesn't seem reasonable as well.

A lot of answers here on SO that talk about yield return use one of these two terms.

What about "generators"? Or does that only apply when you're "conjuring up values out of thin air", e.g. the Fibonacci Numbers where you don't need a data collection as a source?


回答1:


As a general concept in a non-language specific way, "generator" is probably the most common term. That's what I'd use if I were talking to someone who wasn't familiar with C#.

The method itself is an iterator in C# specification terminology. The implementation is an iterator block.

From section 10.14 of the C# 4 spec:

A function member (§7.5) implemented using an iterator block (§8.2) is called an iterator.

That's the terminology I'd use when talking about C# specifically.




回答2:


The principal it is useful for though is "Coroutine". See Wikipedia.

Coroutines are computer program components that generalize subroutines to allow multiple entry points for suspending and resuming execution at certain locations. Coroutines are well-suited for implementing more familiar program components such as cooperative tasks, iterators, infinite lists and pipes.




回答3:


It's called an iterator, check out this MSDN page

An iterator is a method, get accessor, or operator that performs a custom iteration over an array or collection class by using the yield keyword



来源:https://stackoverflow.com/questions/11799572/what-is-the-name-of-the-yield-return-concept-ienumerable-iterator-generator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!