yield return:使用.NET的状态机生成器

通过关键字词组yield return,.Net Framework(从2.0开始)会为我们生成一个状态机.状态机实际上就是一个可枚举的类型化集合

理解yield return的工作方式

  关键字词组yield return是迭代器模式(Iterator Pattern)的一种实现,能够将本身不是可迭代集合的对象做成可迭代集合

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 
 6 namespace SimpleYieldReturn {
 7     class Program {
 8         static void Main(string[] args) {
 9 
10             foreach(int i in GetEvents()) {
11                 Console.WriteLine(i);
12             }
13             Console.Read();
14         }
15 
16         public static IEnumerable<int> GetEvents() {
17             var integers = new[] { 1,2,3,4,5,6,7,8 };
18             foreach(int i in integers) {
19                 if(i % 2 == 0) {
20                     yield return i;
21                 }
22             }
23         }
24     }
25 
26 }
SimpleYieldReturn

GetEvents被当作集合来用,yield return导致编译器自动生成了可枚举类

原文地址:https://www.cnblogs.com/revoid/p/6663922.html