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 ...
随机推荐
- Mysql的两种存储引擎以及区别
一.Mysql的两种存储引擎 1.MyISAM: ①不支持事务,但是整个操作是原子性的(事务具备四种特性:原子性.一致性.隔离性.持久性) ②不支持外键,支持表锁,每次所住的是整张表 MyIS ...
- Django之FBV和CBV的用法
FBV FBV,即 func base views,函数视图,在视图里使用函数处理请求. 以用户注册代码为例, 使用两个函数完成注册 初级注册代码 def register(request): &qu ...
- FaceBook快捷登入
关于集成FaceBook快捷登入,我上回做了个最简单的版本,所有Web端通用,在这边共享下,有更好的解决方案的,麻烦评论留个地址,有不妥之处请指正. 首先,我们先加载Facebook的Js windo ...
- Day 9 用户管理
1.什么是用户? 能正常登陆系统的都算用户 windows系统和linux系统的用户有什么区别? 本质上没有区别, linux支持多个用户同一时刻登陆系统, 互相之间不影 响 而windows只允许同 ...
- Spring Boot(一) Hello World
一.Spring Boot之我见 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从 ...
- jqGrid 日期格式化,只显示日期,去掉小时分
{name:'operateTime',index:'operateTime', formatter:"date", formatoptions: {newformat:'Y-m- ...
- Java常识及数据类型
上次介绍完了JDK的下载,安装,以及配置了环境变量 .这次我们来讲讲Java的常识及Java的数据类型; 常见Java开发工具 编辑器: 1:UltraEdit; 2:EditPlus等; 集成开发环 ...
- java字符串,数组,集合框架重点
1.字符串的字面量是否自动生成一个字符串的变量? String str1 = “abc”; Sring str2 = new String (“abc”); 对于str1:Jvm在遇到双 ...
- wordpress安装主题、插件需要FTP用户名密码
修改主目录wordpress下的wp-config.php文件,在最结尾加上 define("FS_METHOD", "direct"); define(&qu ...
- python2和3区别
核心类差异 Python3对Unicode字符的原生支持 Python2中使用 ASCII 码作为默认编码方式导致string有两种类型str和unicode,Python3只支持unicode的st ...