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 ...
随机推荐
- Python编译器及Sublime Text3安装及开发环境配置
1.初学Python,你需要一个好的开发编辑器 在选择Python编辑器时,可能纠结于那个Python的版本更好一些,在Python2.x和Python3.x版本中, Python3.x版本更好一些, ...
- JAVA截取后String字符串六位字符
public static void main(String[] args){ String cellphone="; String pwd = cellphone.substring(ce ...
- apache ignite系列(三):数据处理(数据加载,数据并置,数据查询)
使用ignite的一个常见思路就是将现有的关系型数据库中的数据导入到ignite中,然后直接使用ignite中的数据,相当于将ignite作为一个缓存服务,当然ignite的功能远不止于此,下面以 ...
- 手把手教程: CentOS 6.5 LVS + KeepAlived 搭建 负载均衡 高可用 集群
为了实现服务的高可用和可扩展,在网上找了几天的资料,现在终于配置完毕,现将心得公布处理,希望对和我一样刚入门的菜鸟能有一些帮助. 一.理论知识(原理) 我们不仅要知其然,而且要知其所以然,所以先给大家 ...
- 遇到XML-GB2312网页编码的处理方法
报的错误:encoding error : input conversion failed due to input error, bytes I/O error : encoder error 1 ...
- Centos7上配置nginx的负载均衡
前言 在配置nginx负载均衡前.我们需要明白几个名词的概念 注: 如果不小心忘了tomcat和nginx的启动,关闭命令,可参考写在文章最后的命令 一 重要的概念理解 1 什么是nginx呢? Ng ...
- django配置静态文件的两种方法
方法一:按照django配置静态文件的方法,可以在APP应用目录下创建一个static的文件夹,然后在static文件夹下创建一个和APP同名的文件夹,如我有一个blog的django项目,在下面有一 ...
- ssh免密码登陆(集群多台机器之间免密码登陆)
1. 首先在配置hosts文件(每台机器都要) 进入root权限 vi /etc/hosts 添加每台机器的ip + 主机名,例如: 172.18.23.201 hadoop1 172.18.23.1 ...
- Python3.7.4入门-0/1To Begin/数据类型与结构
0 To Begin //:向下取整除法 **:乘方 在交互模式下,上一次打印出来的表达式被赋值给变量 _ 如果不希望前置了 \ 的字符转义成特殊字符,可以使用 原始字符串 方式,在引号前添加 r 即 ...
- Django-中间件-csrf扩展请求伪造拦截中间件-Django Auth模块使用-效仿 django 中间件配置实现功能插拔式效果-09
目录 昨日补充:将自己写的 login_auth 装饰装在 CBV 上 django 中间件 django 请求生命周期 ***** 默认中间件及其大概方法组成 中间件的执行顺序 自定义中间件探究不同 ...