C#中關於foreach實現的原理詳解
這篇文章主要為大家詳細介紹了C#中foreach實現原理,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文主要記錄我在學習C#中foreach遍歷原理的心得體會。
對集合中的要素進行遍歷是所有編碼中經常涉及到的操作,因此大部分程式語言都把此過程寫進了語法中,例如C#中的foreach。常常會看到下面的遍歷程式碼:
var lstStr = new List<string> { "a", "b" }; foreach (var str in lstStr) { Console.WriteLine(str); }
實際此程式碼的執行過程:
##
var lstStr = new List<string> {"a", "b"}; IEnumerator<string> enumeratorLst = lstStr.GetEnumerator(); while (enumeratorLst.MoveNext()) { Console.WriteLine(enumeratorLst.Current); }
// 摘要: // 公开枚举器,该枚举器支持在非泛型集合上进行简单迭代。 public interface IEnumerable { // 摘要: // 返回一个循环访问集合的枚举器。 // // 返回结果: // 可用于循环访问集合的 System.Collections.IEnumerator 对象。 IEnumerator GetEnumerator(); }
// 摘要: // 支持对非泛型集合的简单迭代。 public interface IEnumerator { // 摘要: // 获取集合中的当前元素。 // // 返回结果: // 集合中的当前元素。 // // 异常: // System.InvalidOperationException: // 枚举数定位在该集合的第一个元素之前或最后一个元素之后。 object Current { get; } // 摘要: // 将枚举数推进到集合的下一个元素。 // // 返回结果: // 如果枚举数成功地推进到下一个元素,则为 true;如果枚举数越过集合的结尾,则为 false。 // // 异常: // System.InvalidOperationException: // 在创建了枚举数后集合被修改了。 bool MoveNext(); // // 摘要: // 将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。 // // 异常: // System.InvalidOperationException: // 在创建了枚举数后集合被修改了。 void Reset(); }
using System; using System.Collections; // Simple business object. public class Person { public Person(string fName, string lName) { this.firstName = fName; this.lastName = lName; } public string firstName; public string lastName; } // Collection of Person objects. This class // implements IEnumerable so that it can be used // with ForEach syntax. public class People : IEnumerable { private Person[] _people; public People(Person[] pArray) { _people = new Person[pArray.Length]; for (int i = 0; i < pArray.Length; i++) { _people[i] = pArray[i]; } } // Implementation for the GetEnumerator method. IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator) GetEnumerator(); } public PeopleEnum GetEnumerator() { return new PeopleEnum(_people); } } // When you implement IEnumerable, you must also implement IEnumerator. public class PeopleEnum : IEnumerator { public Person[] _people; // Enumerators are positioned before the first element // until the first MoveNext() call. int position = -1; public PeopleEnum(Person[] list) { _people = list; } public bool MoveNext() { position++; return (position < _people.Length); } public void Reset() { position = -1; } object IEnumerator.Current { get { return Current; } } public Person Current { get { try { return _people[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } } class App { static void Main() { Person[] peopleArray = new Person[3] { new Person("John", "Smith"), new Person("Jim", "Johnson"), new Person("Sue", "Rabon"), }; People peopleList = new People(peopleArray); foreach (Person p in peopleList) Console.WriteLine(p.firstName + " " + p.lastName); } } /* This code produces output similar to the following: * * John Smith * Jim Johnson * Sue Rabon * */
using System; using System.Collections; // Simple business object. public class Person { public Person(string fName, string lName) { this.firstName = fName; this.lastName = lName; } public string firstName; public string lastName; } // Collection of Person objects. This class // implements IEnumerable so that it can be used // with ForEach syntax. public class People : IEnumerable { private Person[] _people; public People(Person[] pArray) { _people = new Person[pArray.Length]; for (int i = 0; i < pArray.Length; i++) { _people[i] = pArray[i]; } } // Implementation for the GetEnumerator method. IEnumerator IEnumerable.GetEnumerator() { for (int i = 0; i < _people.Length; i++) { yield return _people[i]; } } } class App { static void Main() { Person[] peopleArray = new Person[3] { new Person("John", "Smith"), new Person("Jim", "Johnson"), new Person("Sue", "Rabon"), }; People peopleList = new People(peopleArray); foreach (Person p in peopleList) Console.WriteLine(p.firstName + " " + p.lastName); } }
以上是C#中關於foreach實現的原理詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

一、Iterator和foreach的區別多態差異(foreach底層就是Iterator)Iterator是一個介面類型,他不關心集合或數組的類型;for和foreach都需要先知道集合的類型,甚至是集合內元素的類型; 1.為啥說foreach底層就是Iterator寫的程式碼:反編譯程式碼:二、foreach與iterator時remove的差別先來看阿里java開發手冊但1的時候不會報錯,2的時候就會報錯(java. util.ConcurrentModificationException)首

php判斷foreach循環到第幾個的步驟:1、創建一個「$fruits」的數組;2、創建一個計數器變數「$counter」初始值為0;3、使用「foreach」循環遍歷數組,並在循環體中增加計數器變數的值,再輸出每個元素和它們的索引;4、在「foreach」循環體外輸出計數器變數的值,以確認循環到了第幾個元素。

當今人工智慧(AI)技術的發展如火如荼,它們在各個領域都展現了巨大的潛力和影響力。今天大姚給大家分享4個.NET開源的AI模型LLM相關的專案框架,希望能為大家提供一些參考。 https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel是一種開源的軟體開發工具包(SDK),旨在將大型語言模型(LLM)如OpenAI、Azure

這篇文章將為大家詳細講解有關PHP返回一個鍵值翻轉後的數組,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章後可以有所收穫。 PHP鍵值翻轉數組鍵值翻轉是一種對數組進行的操作,它將數組中的鍵和值進行交換,產生一個新的數組,其中原始鍵作為值,原始值作為鍵。實作方法在php中,可以透過以下方法對陣列進行鍵值翻轉:array_flip()函數:array_flip()函數專門用於鍵值翻轉操作。它接收一個數組作為參數,並傳回一個新的數組,其中鍵和值已交換。 $original_array=[

這篇文章將為大家詳細講解有關PHP返回數組中的當前元素,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章後可以有所收穫。取得PHP陣列中的目前元素php為存取和操作陣列提供了多種方法,其中包括取得陣列中的目前元素。以下介紹幾種常用的技術:1.current()函數current()函數傳回數組內部指標目前指向的元素。指標最初指向數組的第一個元素。使用下列語法:$currentElement=current($array);2.key()函數key()函數傳回陣列內部指標目前指向元

區別:1、for透過索引來循環遍歷每一個資料元素,而forEach透過JS底層程式來循環遍歷數組的資料元素;2、for可以透過break關鍵字來終止迴圈的執行,而forEach不可以;3、 for可以透過控制迴圈變數的數值來控制迴圈的執行,而forEach不行;4、for在迴圈外可以呼叫迴圈變量,而forEach在迴圈外不能呼叫迴圈變數;5、for的執行效率要高於forEach。

如果你是.NET開發者,你必須意識到在交付高品質軟體方面,優化功能和效能的重要性。透過熟練使用提供的資源並減少網站載入時間,你不僅為使用者創造了愉快的體驗,還能減少基礎設施成本。
