什么是在C#中使用yield关键字?

什么是在C#中使用yield关键字?

问题描述:

我怎么可以公开只有的IList℃的片段;> 问题的答案的人有下列code片断:

In the How Can I Expose Only a Fragment of IList<> question one of the answers had the following code snippet:

IEnumerable<object> FilteredList()
{
    foreach( object item in FullList )
    {
        if( IsItemInPartialList( item )
            yield return item;
    }
}

什么是产量关键字做呢?我见过一对夫妇地方引用,和另外一个问题,但我还没有完全想通了其实际作用。我已经习惯了在一个线程屈服于另一个意义上产量的思维,但似乎并没有与此有关。

What does the yield keyword do there? I've seen it referenced in a couple places, and one other question, but I haven't quite figured out what it actually does. I'm used to thinking of yield in the sense of one thread yielding to another, but that doesn't seem relevant here.

产量关键字居然在这里做了不少。该函数返回实现IEnumerable接口的对象。如果调用函数开始的foreach ING在此对象的函数被调用一次,直到它收益率。这是介绍了C#2.0的语法糖。在早期版本中,你必须创建自己的IEnumerable和IEnumerator的对象做这样的东西。

The yield keyword actually does quite a lot here. The function returns an object that implements the IEnumerable interface. If a calling function starts foreach-ing over this object the function is called again until it "yields". This is syntactic sugar introduced in C# 2.0. In earlier versions you had to create your own IEnumerable and IEnumerator objects to do stuff like this.

最简单的方式了解code这样是输入一个例子,设置一些断点,并看看会发生什么。

The easiest way understand code like this is to type in an example, set some breakpoints and see what happens.

尝试通过这个例如步进:

Try stepping through this for example:

public void Consumer()
{
    foreach(int i in Integers())
    {
        Console.WriteLine(i.ToString());
    }
}

public IEnumerable<int> Integers()
{
    yield return 1;
    yield return 2;
    yield return 4;
    yield return 8;
    yield return 16;
    yield return 16777216;
}