C# Foreach循环本质与枚举器
对于C#里面的Foreach学过 语言的人都知道怎么用,但是其原理相信很多人和我一样都没有去深究。刚回顾泛型讲到枚举器让我联想到了Foreach的实现,所以进行一番探究,有什么不对或者错误的地方大家多多斧正。
1、创建一个控制台应用程序

2、编写测试代码并分析
在Program类中写一个foreach循环
class Program
{
static void Main(string[] args)
{
List peopleList = new List() { "张三", "李四", "王五" };
foreach (string people in peopleList)
{
Console.WriteLine(people);
}
Console.ReadKey();
}
}
生成项目将项目编译后在debug目录下用Reflection反编译ForeachTest.exe程序集后查看Program类的IL代码,IL代码如下:
.class private auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
.maxstack
L_0000: ldarg.
L_0001: call instance void [mscorlib]System.Object::.ctor()
L_0006: ret
} .method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.maxstack
.locals init (
[] class [mscorlib]System.Collections.Generic.List`<string> list,
[] string str,
[] class [mscorlib]System.Collections.Generic.List`<string> list2,
[] valuetype [mscorlib]System.Collections.Generic.List`/Enumerator`<string> enumerator,
[] bool flag)
L_0000: nop
L_0001: newobj instance void [mscorlib]System.Collections.Generic.List`<string>::.ctor()
L_0006: stloc.
L_0007: ldloc.
L_0008: ldstr "\u5f20\u4e09"
L_000d: callvirt instance void [mscorlib]System.Collections.Generic.List`<string>::Add(!)
L_0012: nop
L_0013: ldloc.
L_0014: ldstr "\u674e\u56db"
L_0019: callvirt instance void [mscorlib]System.Collections.Generic.List`<string>::Add(!)
L_001e: nop
L_001f: ldloc.
L_0020: ldstr "\u738b\u4e94"
L_0025: callvirt instance void [mscorlib]System.Collections.Generic.List`<string>::Add(!)
L_002a: nop
L_002b: ldloc.
L_002c: stloc.
L_002d: nop
L_002e: ldloc.
L_002f: callvirt instance valuetype [mscorlib]System.Collections.Generic.List`/Enumerator`<!> [mscorlib]System.Collections.Generic.List`<string>::GetEnumerator()
L_0034: stloc.
L_0035: br.s L_0048
L_0037: ldloca.s enumerator
L_0039: call instance ! [mscorlib]System.Collections.Generic.List`/Enumerator`<string>::get_Current()
L_003e: stloc.
L_003f: nop
L_0040: ldloc.
L_0041: call void [mscorlib]System.Console::WriteLine(string)
L_0046: nop
L_0047: nop
L_0048: ldloca.s enumerator
L_004a: call instance bool [mscorlib]System.Collections.Generic.List`/Enumerator`<string>::MoveNext()
L_004f: stloc.s flag
L_0051: ldloc.s flag
L_0053: brtrue.s L_0037
L_0055: leave.s L_0066
L_0057: ldloca.s enumerator
L_0059: constrained. [mscorlib]System.Collections.Generic.List`/Enumerator`<string>
L_005f: callvirt instance void [mscorlib]System.IDisposable::Dispose()
L_0064: nop
L_0065: endfinally
L_0066: nop
L_0067: call valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey()
L_006c: pop
L_006d: ret
.try L_0035 to L_0057 finally handler L_0057 to L_0066
}
}
在反编译的IL代码中我们看到除了构建List和其他输出,然后多了三个方法:GetEnumerator(),get_Current() ,MoveNext() ,于是通过反编译reflector查看List泛型类,在List里面找到GetEnumerator方法是继承自接口IEnumerable 的方法,List实现的GetEnumerator方法代码
public Enumerator GetEnumerator() => new Enumerator((List) this);
即返回一个Enumerator泛型类,然后传入的参数是List泛型自己 this。接下来查看 Enumerator<T>泛型类
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Enumerator : IEnumerator<T>, IDisposable, IEnumerator
{
private List<T> list;
private int index;
private int version;
private T current;
internal Enumerator(List<T> list)
{
this.list = list;
this.index = ;
this.version = list._version;
this.current = default(T);
} public void Dispose()
{
} public bool MoveNext()
{
List<T> list = this.list;
if ((this.version == list._version) && (this.index < list._size))
{
this.current = list._items[this.index];
this.index++;
return true;
}
return this.MoveNextRare();
} private bool MoveNextRare()
{
if (this.version != this.list._version)
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
this.index = this.list._size + ;
this.current = default(T);
return false;
} public T Current =>
this.current;
object IEnumerator.Current
{
get
{
if ((this.index == ) || (this.index == (this.list._size + )))
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
return this.Current;
}
}
void IEnumerator.Reset()
{
if (this.version != this.list._version)
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
this.index = ;
this.current = default(T);
}
}
我们看到这个Enumerator<T>泛型类实现了接口IEnumerator的方法,也就是我们测试的ForeachTest程序集反编译后IL代码中出现的get_Current() ,MoveNext() 方法。所以foreach实际上是编译器编译后先调用GetEnumerator方法返回Enumerator的实例,这个实例即是一个枚举器实例。通过MoveNext方法移动下标来查找下一个list元素,get_Current方法获取当前查找到的元素,Reset方法是重置list。
3、总结
因此要使用Foreach遍历的对象是继承了IEnumerable接口然后实现GetEnumerator方法。返回的实体对象需要继承IEnumerator接口并实现相应的方法遍历对象。因此Foreach的另一种写法如下。

C# Foreach循环本质与枚举器的更多相关文章
- 反编译看java for-each循环
java 1.5发行版引入的for-each循环.(引自<Effective Java>中文版第二版 第46条) 如以下对数组列表的for-each循环示例: public class F ...
- 涨姿势:深入 foreach循环
我们知道集合中的遍历都是通过迭代(iterator)完成的. 也许有人说,不一定非要使用迭代,如: List<String> list = new LinkedList<String ...
- 集合中的 for-Each循环
数组的加强型的for-Each循环很简单,我们再来看一下集合中的for-Each 循环又是怎么样的.我们都知道集合中的遍历都是通过迭代(iterator)完成的.也许有人说,也可以按照下面的方式来遍 ...
- 接口、索引器、Foreach的本质(学习笔记)
接口 什么是接口? 接口代表一种能力,和抽象类类似但比抽象类的抽象程度更高! 接口的定义: public interface IEat//定义一个接口 { void Eat(string food); ...
- c# foreach枚举器
要是自己的类支持foreach ,必须在类中必须有GetEnumerator方法,该方法返回的是一个IEnumerator类型的枚举器; public class MyStruct { public ...
- C#中的foreach语句与枚举器接口(IEnumerator)及其泛型 相关问题
这个问题从<C#高级编程>数组一节中的foreach语句(6.7.2)发现的. 因为示例代码与之前的章节连贯,所以我修改了一下,把自定义类型改为了int int[] bs = { 2, 3 ...
- C#图解教程 第十八章 枚举器和迭代器
枚举器和迭代器 枚举器和可枚举类型 foreach语句 IEnumerator接口 使用IEnumerable和IEnumerator的示例 泛型枚举接口迭代器 迭代器块使用迭代器来创建枚举器使用迭代 ...
- C#中的枚举器(转)
术语表 Iterator:枚举器(迭代器) 如果你正在创建一个表现和行为都类似于集合的类,允许类的用户使用foreach语句对集合中的成员进行枚举将会是很方便的.这在C# 2.0中比 C# 1.1更容 ...
- C#枚举器接口IEnumerator的实现
原文(http://blog.csdn.net/phpxin123/article/details/7897226) 在C#中,如果一个类要使用foreach结构来实现迭代,就必须实现IEnumera ...
随机推荐
- 湘潭大学oj循环1-5
#include <stdio.h>#include <stdlib.h> int main(){ int b,s,n; int a[101]; A:scanf(&q ...
- HTTPS加密协议
使用JDK自带的keytool工具生成一个证书(keystore文件),其中包含了密钥. a.在命令行输入以下命令:keytool -genkey -alias tbb -keyalg RSA -ke ...
- 使用ECMAScript 6 模块封装代码
JavaScript 用"共享一切"的方法加载代码,这是该语言中最容易出错且最容易让人感到困惑的地方.其他语言使用诸如包这样的概念来定义代码作用域,但在 ECMAScript 6 ...
- 一次误用CSRedisCore引发的redis故障排除经历
前导 上次Redis MQ分布式改造完成之后, 编排的容器稳定运行了一个多月,昨天突然收到ETL端同事通知,没有采集到解析日志了. 赶紧进服务器看了一下,用于数据接收的receiver容器挂掉了, 尝 ...
- 6、二叉树树(java实现)
1.创建树的节点 public class Node { public Object data; //存储数据 public Node leftChild; //左子树指针 public Node r ...
- ACM团队招新赛题解
标程代码全部为C语言编写.代码中的#if LOCAL_ 至#endif为本地一些调试内容,可以忽略. Xenny的A+B(1)[容易][签到] 签到题,做不出的话可能你有点不太适合ACM了. Xenn ...
- MYSQL之概念基础篇
1数据库概述 1.1 数据管理技术的产生和发展 数据库技术是应数据库管理任务的需要而产生的.20世纪50年代中期以前,计算机主要是用于科学计算.当时的硬件状况是,外存只有纸带.卡片.磁带,没有磁盘等可 ...
- Python 爬虫监控女神的QQ空间新的说说,实现邮箱发送
主要实现的功能就是:监控女神的 QQ空间,一旦女神发布新的说说,你的邮箱马上就会收到说说内容,是不是想了解一下 先看看代码运行效果图: PS:只有你有一台云服务器你就可以把程序24h运行起来 直接上代 ...
- flask+layui+echarts实现前端动态图展示数据
效果图: 该效果主要实现一个table展示数据,并在下方生成一个折线图. 实现方式: 1.首先需要对表格进行一个数据加载,这里用到了layui的table.render,具体用法可以参考 https: ...
- 基于C#的机器学习--c# .NET中直观的深度学习
在本章中,将会学到: l 如何使用Kelp.Net来执行自己的测试 l 如何编写测试 l 如何对函数进行基准测试 Kelp.Net是一个用c#编写的深度学习库.由于能够将函数链到函数堆栈中,它在 ...