一、Foreach语句简介

在C# 1.0中我们经常使用foreach来遍历一个集合中的元素,然而如果一个集合要支持使用foreach语句来进行遍历,这个集合一般需要IEnumerable或IEnumerable<T>接口。

因为foreach是迭代语句,要使用foreach必须要有一个迭代器才行的,而IEnumerable接口中的IEnumerator GetEnumerator()方法是返回迭代器的。

在C# 1.0中,要获得迭代器一般需要实现IEnumerable接口中的GetEnumerator()方法,然而要实现一个迭代器就必须实现IEnumerator接口。

在C# 2.0中,提供 yield关键字来简化迭代器的实现。

foreach被编译后会调用GetEnumerator来返回一个迭代器。

二、C#1.0中实现迭代器

  1 using System;
2 using System.Collections;
3
4 namespace 迭代器Demo
5 {
6 class Program
7 {
8 static void Main(string[] args)
9 {
10 Friends friendcollection = new Friends();
11 foreach (Friend f in friendcollection)
12 {
13 Console.WriteLine(f.Name);
14 }
15
16 Console.Read();
17 }
18 }
19
20 /// <summary>
21 /// 朋友类
22 /// </summary>
23 public class Friend
24 {
25 private string name;
26 public string Name
27 {
28 get { return name; }
29 set { name = value; }
30 }
31 public Friend(string name)
32 {
33 this.name = name;
34 }
35 }
36
37 /// <summary>
38 /// 朋友集合
39 /// </summary>
40 public class Friends : IEnumerable
41 {
42 private Friend[] friendarray;
43
44 public Friends()
45 {
46 friendarray = new Friend[]
47 {
48 new Friend("张三"),
49 new Friend("李四"),
50 new Friend("王五")
51 };
52 }
53
54 // 索引器
55 public Friend this[int index]
56 {
57 get { return friendarray[index]; }
58 }
59
60 public int Count
61 {
62 get { return friendarray.Length; }
63 }
64
65 // 实现IEnumerable<T>接口方法
66 public IEnumerator GetEnumerator()
67 {
68 return new FriendIterator(this);
69 }
70 }
71
72 /// <summary>
73 /// 自定义迭代器,必须实现 IEnumerator接口
74 /// </summary>
75 public class FriendIterator : IEnumerator
76 {
77 private readonly Friends friends;
78 private int index;
79 private Friend current;
80 internal FriendIterator(Friends friendcollection)
81 {
82 this.friends = friendcollection;
83 index = 0;
84 }
85
86 #region 实现IEnumerator接口中的方法
87 public object Current
88 {
89 get
90 {
91 return this.current;
92 }
93 }
94
95 public bool MoveNext()
96 {
97 if (index + 1 > friends.Count)
98 {
99 return false;
100 }
101 else
102 {
103 this.current = friends[index];
104 index++;
105 return true;
106 }
107 }
108
109 public void Reset()
110 {
111 index = 0;
112 }
113
114 #endregion
115 }
116 }

三、C#2.0中实现迭代器

 1 namespace 简化迭代器的实现
2 {
3 class Program
4 {
5 static void Main(string[] args)
6 {
7 Friends friendcollection = new Friends();
8 foreach (Friend f in friendcollection)
9 {
10 Console.WriteLine(f.Name);
11 }
12
13 Console.Read();
14 }
15 }
16
17 /// <summary>
18 /// 朋友类
19 /// </summary>
20 public class Friend
21 {
22 private string name;
23 public string Name
24 {
25 get { return name; }
26 set { name = value; }
27 }
28 public Friend(string name)
29 {
30 this.name = name;
31 }
32 }
33
34 /// <summary>
35 /// 朋友集合
36 /// </summary>
37 public class Friends : IEnumerable
38 {
39 private Friend[] friendarray;
40
41 public Friends()
42 {
43 friendarray = new Friend[]
44 {
45 new Friend("张三"),
46 new Friend("李四"),
47 new Friend("王五")
48 };
49 }
50
51 // 索引器
52 public Friend this[int index]
53 {
54 get { return friendarray[index]; }
55 }
56
57 public int Count
58 {
59 get { return friendarray.Length; }
60 }
61
62 // C# 2.0中简化迭代器的实现
63 public IEnumerator GetEnumerator()
64 {
65 for (int index = 0; index < friendarray.Length; index++)
66 {
67 // 这样就不需要额外定义一个FriendIterator迭代器来实现IEnumerator
68 // 在C# 2.0中只需要使用下面语句就可以实现一个迭代器
69 yield return friendarray[index];
70 }
71 }
72 }
73 }

在上面代码中有一个yield return 语句,这个语句的作用就是告诉编译器GetEnumerator方法不是一个普通的方法,而是实现一个迭代器的方法。

当编译器看到yield return语句时,编译器知道需要实现一个迭代器,所以编译器生成中间代码时为我们生成了一个实现IEnumerator接口的内部类。

大家可以通过Reflector工具进行查看,下面是通过Reflector工具得到一张截图:

四、迭代器执行过程

注:本文参考http://www.cnblogs.com/zhili/archive/2012/12/02/Interator.html

C#基础知识---迭代器与Foreach语句的更多相关文章

  1. C#基础知识 yield与foreach

    什么时候可以使用yield的关键字来定义迭代器? 迭代器的返回类型必须是IEnumerable.IEnumerable<T>.IEnumerator 或 IEnumerator<T& ...

  2. PHP基础知识之————PDO预处理语句

    转载处:http://www.cnblogs.com/xiaohuochai/p/6133353.html 定义 在生成网页时,许多PHP脚本通常都会执行除参数之外,其他部分完全相同的查询语句,针对这 ...

  3. python基础知识---迭代器、生成器、装饰器

    一.迭代器 二.生成器 http://www.cnblogs.com/huxi/archive/2011/07/14/2106863.html def func(): #定义生成器,和普通函数的区别是 ...

  4. 1.17 Python基础知识 - 迭代器和生成器初识

    可循环迭代的对象称为可迭代对象,迭代器和生成器函数是可迭代对象. 列表解析表达式:可以简单高效处理一个可迭代对象,并生成结果列表 示例代码: [ i ** 2 for i in range(10) ] ...

  5. C# 篇基础知识11——泛型和集合

    .NET提供了一级功能强大的集合类,实现了多种不同类型的集合,可以根据实际用途选择恰当的集合类型. 除了数组 Array 类定义在System 命名空间中外,其他的集合类都定义在System.Coll ...

  6. MySQL数据库基础知识及优化

    MySQL数据库基础知识及优化必会的知识点,你掌握了多少? 推荐阅读: 这些必会的计算机网络知识点你都掌握了吗 关于数据库事务和锁的必会知识点,你掌握了多少? 关于数据库索引,必须掌握的知识点 目录 ...

  7. 第4章 基础知识进阶 第4.1节 Python基础概念之迭代、可迭代对象、迭代器

    第四章 基础知识进阶第十七节 迭代.可迭代对象.迭代器 一.    引言 本来计划讲完元组和字典后就讲列表解析和字典解析,但要理解列表解析和字典解析,就需要掌握Python的高级的类型迭代器,因此本节 ...

  8. C#中foreach语句的迭代器实现机制

    C#中的foreach语句可用于循环遍历某个集合中的元素,而所有的只要支持了IEnumerable或IEnumerable<T>泛型接口的类型都是可以 用foreach遍历的.其具体的遍历 ...

  9. 常见SQL语句和SQL基础知识

    引自:http://blog.csdn.net/u012467492/article/details/46790205 SQL语句考察(一) 1.查询出每门课都大于80 分的学生姓名 name   k ...

随机推荐

  1. shell脚本(2)-shell脚本语法

    一.如何抒写shell脚本 1.shell脚本的命名 名字要有意义,不要以a.b.c.1.2.3这种方式命令,建议以sh结尾,在30个字节内,例如:check_memory.sh  2.shell脚本 ...

  2. Spring Boot(二):Spring Boot中的配置参数

    Spring Boot 配置参数 Spring Boot 帮助我们完成了许许多多的自动化配置 如果我们需要根据自己的需求修改配置 也是可以的 可以使用.properties 和 .yml 格式配置 这 ...

  3. js中 typeof 和 instanceof 的区别

    typeof 和 instanceof 都能判断数据类型,但是它们之间有什么区别呢,浅谈如下 typeof 用于判断数据类型,返回值为以下6种类型 1.string 2.boolean 3.numbe ...

  4. 一:Vue项目构建

    第一步:需要安装nodeJS的环境,直接去官网下载https://nodejs.org/en/,下载下来按照提示一步步的安装.(vue.js是一个Js 框架.在node里面通过Npm 安装,是为了方便 ...

  5. Python (paramiko) 连接Linux服务器

    目录 参考资料 Paramiko 安装 连接Linux 文件上传/下载 文件封装 其他 参考资料 https://www.liujiangblog.com/blog/15/ https://blog. ...

  6. CF404D-DP【成就达成】

    CF404D-DP 正经的东西 题意 给定一个字符串,只包含'0','1','2','*','?'五种字符,其中'?'可被替换为其他任何一种,求使序列符合扫雷地图定义的方案数. 一个数字字符大小表示与 ...

  7. Servlet 单例多线程详解(六)

    一.Servlet 单例多线程 Servlet如何处理多个请求访问?Servlet容器默认是采用单实例多线程的方式处理多个请求的:1.当web服务器启动的时候(或客户端发送请求到服务器时),Servl ...

  8. cytoscape-d3-force api

    { animate:true,//是否在布局运行时显示布局:特殊的"结束"值使布局具有离散布局的动画效果 maxIterations:0,//布局退出前的最大迭代次数 maxSim ...

  9. js 调用json

    url = "/plus/API/"; try { // 此处是可能产生例外的语句 } catch(error) { // 此处是负责例外处理的语句 } finally { // ...

  10. PHP判断访问者手机移动端还是PC端的函数

    *移动端判断*/ function isMobile() { // 如果有HTTP_X_WAP_PROFILE则一定是移动设备 if (isset ($_SERVER['HTTP_X_WAP_PROF ...