What are real life applications of yield?

前端 未结 7 1841
梦谈多话
梦谈多话 2020-12-15 23:12

I know what yield does, and I\'ve seen a few examples, but I can\'t think of real life applications, have you used it to solve some specific problem?

(I

7条回答
  •  独厮守ぢ
    2020-12-15 23:44

    LINQ's operators on the Enumerable class are implemented as iterators that are created with the yield statement. It allows you to chain operations like Select() and Where() without actually enumerating anything until you actually use the enumerator in a loop, typically by using the foreach statement. Also, since only one value is computed when you call IEnumerator.MoveNext() if you decide to stop mid-collection, you'll save the performance hit of calculating all of the results.

    Iterators can also be used to implement other kinds of lazy evaluation where expressions are evaluated only when you need it. You can also use yield for more fancy stuff like coroutines.

提交回复
热议问题