C#中Foreach循環(huán)遍歷的本質(zhì)與枚舉器詳解
前言
對(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)文章希望大家以后多多支持腳本之家!
- C# 9.0新特性——擴(kuò)展方法GetEnumerator支持foreach循環(huán)
- c#中l(wèi)ist.FindAll與for循環(huán)的性能對(duì)比總結(jié)
- C#中foreach循環(huán)對(duì)比f(wàn)or循環(huán)的優(yōu)勢(shì)和劣勢(shì)
- 淺談C#中的for循環(huán)與foreach循環(huán)
- C# for循環(huán)的經(jīng)典案例集錦
- C# winform循環(huán)播放多個(gè)視頻
- C#使用for循環(huán)移除HTML標(biāo)記
- c# for循環(huán)中創(chuàng)建線程執(zhí)行問(wèn)題
相關(guān)文章
C#特性-迭代器(上)及一些研究過(guò)程中的副產(chǎn)品
這篇文章主要介紹了C#特性-迭代器(上)及一些研究過(guò)程中的副產(chǎn)品,需要的朋友可以參考下2014-12-12Unity實(shí)現(xiàn)簡(jiǎn)單場(chǎng)景分層移動(dòng)
這篇文章主要為大家詳細(xì)介紹了Unity實(shí)現(xiàn)簡(jiǎn)單場(chǎng)景分層移動(dòng),分為前景、場(chǎng)景、背景等,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09解決unity rotate旋轉(zhuǎn)物體 限制物體旋轉(zhuǎn)角度的大坑
這篇文章主要介紹了解決unity rotate旋轉(zhuǎn)物體 限制物體旋轉(zhuǎn)角度的大坑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04C#獲取局域網(wǎng)MAC地址的簡(jiǎn)單實(shí)例
這篇文章主要介紹了C#獲取局域網(wǎng)MAC地址的簡(jiǎn)單實(shí)例,有需要的朋友可以參考一下2013-11-11C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析
這篇文章主要介紹了C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析,以實(shí)例形式較為詳細(xì)的講述了.NET Framework里面提供的三種Timer具體用法,需要的朋友可以參考下2014-10-10unity通過(guò)Mesh網(wǎng)格繪制圖形(三角形、正方體、圓柱)
這篇文章主要為大家詳細(xì)介紹了unity通過(guò)Mesh網(wǎng)格繪制圖形:三角形、正方體、圓柱,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11