Where it is preferred to use yield return in c#?

This question already has an answer here:

  • What is the yield keyword used for in C#? 16 answers

  • is it just because it saves me a row of a list declaration?

    No. When you use yield you get Deferred Execution. This means that you create the items to yield as the consumer is consuming the items.

    If you add items to the list and then return it, then you have to create all items before the consumer can consume any of them.

    For example, assume that the consumer calls your method and uses a for loop to consume it like this:

    foreach(var item in GetMyLovelyItems())
    {
       ...
    }
    

    If the GetMyLovelyItems returns a list, then all items will be created before the GetMyLovelyItems method returns and the loop starts.

    If on the other hand, you use yield to return items, then the items will be created as the loop goes from one iteration to the next one.


    它也可能与生成收益的代码的延迟/缓冲执行相结合


    It's for those complicated cases where you cannot make due with an array, a list or the Enumerable.* methods. This feature is needed quite rarely.

    The most common usage pattern is emitting items in some kind of loop that cannot be expressed with the Enumerable.* methods.

    Many Enumerable methods are implemented with yield .

    yield is not required for deferred execution . Enumerable is deferred as well.

    In any case you can write your own IEnumerable derived class. This is the most expressive and the most tedious way to produce a sequence.

    链接地址: http://www.djcxy.com/p/9088.html

    上一篇: 在C#中理解产量问题

    下一篇: 哪里最好在c#中使用yield return?