What is the yield keyword used for in C#?

后端 未结 17 1649
盖世英雄少女心
盖世英雄少女心 2020-11-22 05:26

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

IEnumerable FilteredList()
{
         


        
      
      
      
17条回答
  •  既然无缘
    2020-11-22 06:01

    Recently Raymond Chen also ran an interesting series of articles on the yield keyword.

    • The implementation of iterators in C# and its consequences (part 1)
    • The implementation of iterators in C# and its consequences (part 2)
    • The implementation of iterators in C# and its consequences (part 3)
    • The implementation of iterators in C# and its consequences (part 4)

    While it's nominally used for easily implementing an iterator pattern, but can be generalized into a state machine. No point in quoting Raymond, the last part also links to other uses (but the example in Entin's blog is esp good, showing how to write async safe code).

提交回复
热议问题