首页 > 其他 > 详细

LINQ编程技术内幕 通用部分 学习

时间:2017-04-03 23:56:27      阅读:365      评论:0      收藏:0      [点我收藏+]

通过关键字词组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导致编译器自动生成了可枚举类

技术分享

技术分享

LINQ编程技术内幕 通用部分 学习

原文:http://www.cnblogs.com/revoid/p/6663922.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!