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代码如下:

 1 .class private auto ansi beforefieldinit Program
 2     extends [mscorlib]System.Object
 3 {
 4     .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
 5     {
 6         .maxstack 8
 7         L_0000: ldarg.0
 8         L_0001: call instance void [mscorlib]System.Object::.ctor()
 9         L_0006: ret
10     }
11
12     .method private hidebysig static void Main(string[] args) cil managed
13     {
14         .entrypoint
15         .maxstack 2
16         .locals init (
17             [0] class [mscorlib]System.Collections.Generic.List`1<string> list,
18             [1] string str,
19             [2] class [mscorlib]System.Collections.Generic.List`1<string> list2,
20             [3] valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator`0<string> enumerator,
21             [4] bool flag)
22         L_0000: nop
23         L_0001: newobj instance void [mscorlib]System.Collections.Generic.List`1<string>::.ctor()
24         L_0006: stloc.2
25         L_0007: ldloc.2
26         L_0008: ldstr "\u5f20\u4e09"
27         L_000d: callvirt instance void [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
28         L_0012: nop
29         L_0013: ldloc.2
30         L_0014: ldstr "\u674e\u56db"
31         L_0019: callvirt instance void [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
32         L_001e: nop
33         L_001f: ldloc.2
34         L_0020: ldstr "\u738b\u4e94"
35         L_0025: callvirt instance void [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
36         L_002a: nop
37         L_002b: ldloc.2
38         L_002c: stloc.0
39         L_002d: nop
40         L_002e: ldloc.0
41         L_002f: callvirt instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator`0<!0> [mscorlib]System.Collections.Generic.List`1<string>::GetEnumerator()
42         L_0034: stloc.3
43         L_0035: br.s L_0048
44         L_0037: ldloca.s enumerator
45         L_0039: call instance !0 [mscorlib]System.Collections.Generic.List`1/Enumerator`0<string>::get_Current()
46         L_003e: stloc.1
47         L_003f: nop
48         L_0040: ldloc.1
49         L_0041: call void [mscorlib]System.Console::WriteLine(string)
50         L_0046: nop
51         L_0047: nop
52         L_0048: ldloca.s enumerator
53         L_004a: call instance bool [mscorlib]System.Collections.Generic.List`1/Enumerator`0<string>::MoveNext()
54         L_004f: stloc.s flag
55         L_0051: ldloc.s flag
56         L_0053: brtrue.s L_0037
57         L_0055: leave.s L_0066
58         L_0057: ldloca.s enumerator
59         L_0059: constrained. [mscorlib]System.Collections.Generic.List`1/Enumerator`0<string>
60         L_005f: callvirt instance void [mscorlib]System.IDisposable::Dispose()
61         L_0064: nop
62         L_0065: endfinally
63         L_0066: nop
64         L_0067: call valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey()
65         L_006c: pop
66         L_006d: ret
67         .try L_0035 to L_0057 finally handler L_0057 to L_0066
68     }
69 }

在反编译的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 = 0;
        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 + 1;
        this.current = default(T);
        return false;
    }

    public T Current =>
        this.current;
    object IEnumerator.Current
    {
        get
        {
            if ((this.index == 0) || (this.index == (this.list._size + 1)))
            {
                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
            }
            return this.Current;
        }
    }
    void IEnumerator.Reset()
    {
        if (this.version != this.list._version)
        {
            ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
        }
        this.index = 0;
        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的另一种写法如下。

原文地址:https://www.cnblogs.com/SunSpring/p/9829298.html

时间: 2024-08-28 19:19:16

C# Foreach循环本质与枚举器的相关文章

oc语法-枚举器

2015-05-14 22:20:56 1:基于块的枚举 枚举器---循环 1 //使用枚举器进行循环操作 2 NSArray* array = @[@"aa",@"bb",@"cc",@"dd",@"ee",@"ff",@"gg"]; 3 [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL

集合中的 for-Each循环

 数组的加强型的for-Each循环很简单,我们再来看一下集合中的for-Each 循环又是怎么样的.我们都知道集合中的遍历都是通过迭代(iterator)完成的.也许有人说,也可以按照下面的方式来遍历集合,不一定非要使用迭代: 1 List<String> list = new LinkedList<String>(); 2 list.add("a"); 3 list.add("b"); 4 list.add("c");

SSIS【Foreach 循环容器_Foreach 文件枚举器】(导入路径下的所有txt文件的内容) (转)

原文:http://blog.csdn.net/kk185800961/article/details/12276449 SQLServer 2008 R2 SSIS_Foreach 循环容器_Foreach 文件枚举器(导入路径下的所有txt文件的内容) 1. 拖动一个 [Foreach 循环容器]到[控制流]中,再拖动一个[数据流任务]到[Foreach 循环容器]中.如图: 2.编辑[Foreach 循环容器],在选项[集合]中选择[Foreach 文件枚举器],配置要遍历的文件夹及文件类

接口、索引器、Foreach的本质(学习笔记)

接口 什么是接口? 接口代表一种能力,和抽象类类似但比抽象类的抽象程度更高! 接口的定义: 1 public interface IEat//定义一个接口 2 { 3 void Eat(string food);//为该接口定义一种能力 4 } 接口的定义 从上边的例子中我们可以看到,接口中的方法是没有方法体的甚至连访问修饰符都没有.而且在接口中只能有方法.属性.索引器及事件! 接口的使用: 1 public class Dog:IEat //Dog类实现IEat接口 2 { 3 //Dog类实

c# foreach枚举器

要是自己的类支持foreach ,必须在类中必须有GetEnumerator方法,该方法返回的是一个IEnumerator类型的枚举器; public class MyStruct { public string[] sName = new string[] { "张三", "李四", "王五" }; public IEnumerator GetEnumerator() { return new MyStructEnumerator(sName)

多线程下的for循环和foreach循环 System.InvalidOperationException: 集合已修改;可能无法执行枚举

背景:当循环体在循环的时候有需求要修改自己.或者在多线程下,循环静态变量的时候,别人很容易修改了循环体内的数据.但是这就会报错的 准备:for:foeach:多线程. 解决方案:For循环是线程安全的,foreach是线程不安全的.说起开好像很高大上哈.意思是在循环内如,如果调用他们自己的循环体.前者是可以的,但是后者是不行的. 再者如果你循环的是字典.字典是键值对的形式,所以采用线程安全的字典ConcurrentDictionary的字典也可以一定程度的解决问题.但是做好的方案还是添加锁 1,

C# 枚举器

1:枚举器和可枚举类型 我们知道使用foreach可以遍历数组中的元素.那么为什么数组可以被foreach语句处理呢,下面我们就进行讨论一下这个问题. 2:使用foreach语句 我们知道当我们使用foreach语句的时候,这个语句为我们依次取出了数组中的每一个元素. 例如下面的代码: 1 int[] arr = { 1, 2, 3, 4, 5, 6 }; 2 foreach( int arry in arr ) 3 { 4 Console.WriteLine("Array Value::{0}

枚举器和linq

Iterator:枚举器 如果你正在创建一个表现和行为都类似于集合的类,允许类的用户使用foreach语句对集合中的成员进行枚举将会是很方便的. 我们将以创建一个简单化的List Box作为开始,它将包含一个8字符串的数组和一个整型,这个整型用于记录数组中已经添加了多少字符串.构造函数将对数组进行初始化并使用传递进来的参数填充它. using System; using System.Collections; using System.Collections.Generic; using Sys

IEnumerable公开枚举器

// 摘要: //     公开枚举器,该枚举器支持在非泛型集合上进行简单迭代. [ComVisible(true)] [Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")] public interface IEnumerable { // 摘要: //     返回一个循环访问集合的枚举器. // // 返回结果: //     可用于循环访问集合的 System.Collections.IEnumerator 对象. [DispId(-4)]