-1

I came across these two code snippets while reading about IEnumerable interfaces. I would like to understand the exact difference between them in simple terms.

Snippet 1 : without yield,

    public IEnumerator GetEnumerator()
    {
        // Return the array object's IEnumerator.
        return carArray.GetEnumerator();
    }

Snippet 2:with yield,

    public IEnumerator GetEnumerator()
    {
        foreach (Car c in carArray)
        {
            yield return c;
        }
    }

Both the snippets do the same work, So whats so specific in using YIELD over here?

Thanks in advance :)

4

3 回答 3

1

yield return turns your stateful sequential code into an iterator.

Instead of having a separate class to manage the iterator position, like in the first example, you can iterate in code and "return" each value as you visit it. This is not a conventional return, it's a yield which is more of a context switch to the code calling you. The next iteration will resume you.

于 2014-03-29T12:11:01.797 回答
1

本质yield是,它将实际执行推迟到真正查询值的时间。换句话说,不是在您请求enumerator时评估特定值,而是在检索该时(惰性评估)。

这有很多含义:

  • 无需(可能是巨大的)资源分配来预先构建集合
  • 当枚举提前终止时,决不能返回从未查询过的值
于 2014-03-29T12:15:58.140 回答
0

啊,但是有区别!yield return是一种语法糖,可以将控制权交还给调用函数。它提供了优化机会,因此如果您知道要在集合中查找某个值,则不必将整个集合返回给调用者,一旦获得所需内容,就可以将枚举短路。

那么它是如何做到的呢?yield return变成一个 switch 语句,如下所述:http: //startbigthinksmall.wordpress.com/2008/06/09/behind-the-scenes-of-the-c-yield-keyword/

有一个非常好的视频也在这里解释它:https ://www.youtube.com/watch?v=Or9g8LOhXhg

于 2014-03-29T12:17:56.063 回答