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

理解yield return的工作方式

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

yield return:使用.NET的状态机生成器yield return:使用.NET的状态机生成器
 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导致编译器自动生成了可枚举类

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

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

相关文章:

  • 2021-08-20
  • 2021-10-17
  • 2021-07-14
  • 2022-12-23
  • 2021-05-31
  • 2021-07-31
  • 2021-08-13
  • 2022-02-28
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-15
  • 2021-04-14
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案