欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#中Foreach循環(huán)遍歷的本質(zhì)與枚舉器詳解

 更新時(shí)間:2021年08月10日 12:34:19   作者:SpringSun  
這篇文章主要給大家介紹了關(guān)于C#中Foreach循環(huán)遍歷本質(zhì)與枚舉器的相關(guān)資料,foreach循環(huán)用于列舉出集合中所有的元素,foreach語(yǔ)句中的表達(dá)式由關(guān)鍵字in隔開(kāi)的兩個(gè)項(xiàng)組成,本文通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下

前言

對(duì)于C#里面的Foreach學(xué)過(guò) 語(yǔ)言的人都知道怎么用,但是其原理相信很多人和我一樣都沒(méi)有去深究。剛回顧泛型講到枚舉器讓我聯(lián)想到了Foreach的實(shí)現(xiàn),所以進(jìn)行一番探究,有什么不對(duì)或者錯(cuò)誤的地方大家多多斧正。

1、創(chuàng)建一個(gè)控制臺(tái)應(yīng)用程序

2、編寫(xiě)測(cè)試代碼并分析

在Program類(lèi)中寫(xiě)一個(gè)foreach循環(huán)

class Program
{
    static void Main(string[] args)
    {
        List peopleList = new List() { "張三", "李四", "王五" };
        foreach (string people in peopleList)
        {
            Console.WriteLine(people);
        }
        Console.ReadKey();
    }
}

生成項(xiàng)目將項(xiàng)目編譯后在debug目錄下用Reflection反編譯ForeachTest.exe程序集后查看Program類(lèi)的IL代碼,IL代碼如下:

.class private auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
    {
        .maxstack 8
        L_0000: ldarg.0
        L_0001: call instance void [mscorlib]System.Object::.ctor()
        L_0006: ret
    }

    .method private hidebysig static void Main(string[] args) cil managed
    {
        .entrypoint
        .maxstack 2
        .locals init (
            [0] class [mscorlib]System.Collections.Generic.List`1<string> list,
            [1] string str,
            [2] class [mscorlib]System.Collections.Generic.List`1<string> list2,
            [3] valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator`0<string> enumerator,
            [4] bool flag)
        L_0000: nop
        L_0001: newobj instance void [mscorlib]System.Collections.Generic.List`1<string>::.ctor()
        L_0006: stloc.2
        L_0007: ldloc.2
        L_0008: ldstr "\u5f20\u4e09"
        L_000d: callvirt instance void [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
        L_0012: nop
        L_0013: ldloc.2
        L_0014: ldstr "\u674e\u56db"
        L_0019: callvirt instance void [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
        L_001e: nop
        L_001f: ldloc.2
        L_0020: ldstr "\u738b\u4e94"
        L_0025: callvirt instance void [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
        L_002a: nop
        L_002b: ldloc.2
        L_002c: stloc.0
        L_002d: nop
        L_002e: ldloc.0
        L_002f: callvirt instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator`0<!0> [mscorlib]System.Collections.Generic.List`1<string>::GetEnumerator()
        L_0034: stloc.3
        L_0035: br.s L_0048
        L_0037: ldloca.s enumerator
        L_0039: call instance !0 [mscorlib]System.Collections.Generic.List`1/Enumerator`0<string>::get_Current()
        L_003e: stloc.1
        L_003f: nop
        L_0040: ldloc.1
        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`1/Enumerator`0<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`1/Enumerator`0<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代碼中我們看到除了構(gòu)建List和其他輸出,然后多了三個(gè)方法:GetEnumerator(),get_Current() ,MoveNext() ,于是通過(guò)反編譯reflector查看List泛型類(lèi),在List里面找到GetEnumerator方法是繼承自接口IEnumerable 的方法,List實(shí)現(xiàn)的GetEnumerator方法代碼

public Enumerator GetEnumerator() => new Enumerator((List) this);

即返回一個(gè)Enumerator泛型類(lèi),然后傳入的參數(shù)是List泛型自己 this。接下來(lái)查看 Enumerator<T>泛型類(lèi)

[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);
    }
}

我們看到這個(gè)Enumerator<T>泛型類(lèi)實(shí)現(xiàn)了接口IEnumerator的方法,也就是我們測(cè)試的ForeachTest程序集反編譯后IL代碼中出現(xiàn)的get_Current() ,MoveNext() 方法。所以foreach實(shí)際上是編譯器編譯后先調(diào)用GetEnumerator方法返回Enumerator的實(shí)例,這個(gè)實(shí)例即是一個(gè)枚舉器實(shí)例。通過(guò)MoveNext方法移動(dòng)下標(biāo)來(lái)查找下一個(gè)list元素,get_Current方法獲取當(dāng)前查找到的元素,Reset方法是重置list。

3、總結(jié)

因此要使用Foreach遍歷的對(duì)象是繼承了IEnumerable接口然后實(shí)現(xiàn)GetEnumerator方法。返回的實(shí)體對(duì)象需要繼承IEnumerator接口并實(shí)現(xiàn)相應(yīng)的方法遍歷對(duì)象。因此Foreach的另一種寫(xiě)法如下。

到此這篇關(guān)于C#中Foreach循環(huán)遍歷本質(zhì)與枚舉器的文章就介紹到這了,更多相關(guān)C# Foreach循環(huán)與枚舉器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論