IEnumerator和IEnumerable詳解

来源:https://www.cnblogs.com/blueberryzzz/archive/2018/03/28/8667261.html
-Advertisement-
Play Games

IEnumerator和IEnumerable 從名字常來看,IEnumerator是枚舉器的意思,IEnumerable是可枚舉的意思。 瞭解了兩個介面代表的含義後,接著看源碼: IEnumerator: IEnumerable: 發現IEnumerable只有一個GetEnumerator函數, ...


IEnumerator和IEnumerable

從名字常來看,IEnumerator是枚舉器的意思,IEnumerable是可枚舉的意思。
瞭解了兩個介面代表的含義後,接著看源碼:
IEnumerator:

public interface IEnumerator
    {
        // Interfaces are not serializable
        // Advances the enumerator to the next element of the enumeration and
        // returns a boolean indicating whether an element is available. Upon
        // creation, an enumerator is conceptually positioned before the first
        // element of the enumeration, and the first call to MoveNext 
        // brings the first element of the enumeration into view.
        // 
        bool MoveNext();
    
        // Returns the current element of the enumeration. The returned value is
        // undefined before the first call to MoveNext and following a
        // call to MoveNext that returned false. Multiple calls to
        // GetCurrent with no intervening calls to MoveNext 
        // will return the same object.
        // 
        Object Current {
            get; 
        }
    
        // Resets the enumerator to the beginning of the enumeration, starting over.
        // The preferred behavior for Reset is to return the exact same enumeration.
        // This means if you modify the underlying collection then call Reset, your
        // IEnumerator will be invalid, just as it would have been if you had called
        // MoveNext or Current.
        //
        void Reset();
    }

IEnumerable:

    public interface IEnumerable
    {
        // Interfaces are not serializable
        // Returns an IEnumerator for this enumerable Object.  The enumerator provides
        // a simple way to access all the contents of a collection.
        [Pure]
        [DispId(-4)]
        IEnumerator GetEnumerator();
    }

發現IEnumerable只有一個GetEnumerator函數,返回值是IEnumerator類型,從註釋我們可以得知IEnumerable代表繼承此介面的類可以獲取一個IEnumerator來實現枚舉這個類中包含的集合中的元素的功能(比如List<T>,ArrayList,Dictionary等繼承了IEnumeratble介面的類)。

用foreach來瞭解IEnumerable,IEnumerator的工作原理

我們模仿ArrayList來實現一個簡單的ConstArrayList,然後用foreach遍歷。

//一個常量的數組,用於foreach遍歷
class ConstArrayList : IEnumerable
{
    public int[] constItems = new int[] { 1, 2, 3, 4, 5 };
    public IEnumerator GetEnumerator()
    {
        return new ConstArrayListEnumeratorSimple(this);
    }
}
//這個常量數組的迭代器
class ConstArrayListEnumeratorSimple : IEnumerator
{
    ConstArrayList list;
    int index;
    int currentElement;
    public ConstArrayListEnumeratorSimple(ConstArrayList _list)
    {
        list = _list;
        index = -1;
    }

    public object Current
    {
        get
        {
            return currentElement;
        }
    }

    public bool MoveNext()
    {
        if(index < list.constItems.Length - 1)
        {
            currentElement = list.constItems[++index];
            return true;
        }
        else
        {
            currentElement = -1;
            return false;
        }
    }

    public void Reset()
    {
        index = -1;
    }
}
class Program
{    
    static void Main(string[] args)
    {
        ConstArrayList constArrayList = new ConstArrayList();
        foreach(int item in constArrayList)
        {
            WriteLine(item);
        }
        ReadKey();
    }
}

輸出結果:
1
2
3
4
5

代碼達到了遍歷效果,但是在用foreach遍歷時,IEnumerator和IEnumerable究竟是如何運行的,我們可以通過增加增加日誌可以直觀的看到原因。

//一個常量的數組,用於foreach遍歷
class ConstArrayList : IEnumerable
{
    public int[] constItems = new int[] { 1, 2, 3, 4, 5 };
    public IEnumerator GetEnumerator()
    {
        WriteLine("GetIEnumerator");
        return new ConstArrayListEnumeratorSimple(this);
    }
}
//這個常量數組的迭代器
class ConstArrayListEnumeratorSimple : IEnumerator
{
    ConstArrayList list;
    int index;
    int currentElement;
    public ConstArrayListEnumeratorSimple(ConstArrayList _list)
    {
        list = _list;
        index = -1;
    }

    public object Current
    {
        get
        {
            WriteLine("Current");
            return currentElement;
        }
    }

    public bool MoveNext()
    {
        if(index < list.constItems.Length - 1)
        {
            WriteLine("MoveNext true");   
            currentElement = list.constItems[++index];
            return true;
        }
        else
        {
            WriteLine("MoveNext false");
            currentElement = -1;
            return false;
        }
    }

    public void Reset()
    {
        WriteLine("Reset");
        index = -1;
    }
}
class Program
{    
    static void Main(string[] args)
    {
        ConstArrayList constArrayList = new ConstArrayList();
        foreach(int item in constArrayList)
        {
            WriteLine(item);
        }
        ReadKey();
    }
}

輸出結果:
GetIEnumerator
MoveNext true
Current
1
MoveNext true
Current
2
MoveNext true
Current
3
MoveNext true
Current
4
MoveNext true
Current
5
MoveNext false

通過輸出結果,我們可以發現,foreach在運行時會先調用ConstArrayList的GetIEnumerator函數獲取一個ConstArrayListEnumeratorSimple,之後通過迴圈調用ConstArrayListEnumeratorSimple的MoveNext函數,index後移,更新Current屬性,然後返回Current屬性,直到MoveNext返回false。

總結一下:
GetIEnumerator()負責獲取枚舉器。
MoveNext()負責讓Current獲取下一個值,並判斷遍歷是否結束。
Current負責返回當前指向的值。
Rest()負責重置枚舉器的狀態(在foreach中沒有用到)
這些就是IEnumerable,IEnumerator的基本工作原理了。

其次我們發現:

ConstArrayList constArrayList = new ConstArrayList();
foreach(int item in constArrayList)
{
    writeLine(item);
}

其實就等價於:

ConstArrayList constArrayList = new ConstArrayList();
IEnumerator enumeratorSimple = constArrayList.GetEnumerator();
while (enumeratorSimple.MoveNext())
{
    int item = (int)enumeratorSimple.Current;
    WriteLine(item);
}

也就是說foreach其實是一種語法糖,用來簡化對可枚舉元素的遍歷代碼。而被遍歷的類通過實現IEnumerable介面和一個相關的IEnumerator枚舉器來實現遍歷功能。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 學習目的: MongoDB的安裝 正式步驟 (VMWare 虛擬機上無法安裝這個MongoDB的自啟動服務,如果你能辦到,請多賜教) Step1:MongoDB的簡介 MongoDB是一個基於分散式文件存儲的資料庫。由C++語言編寫。旨在為WEB應用提供可擴展的高性能數據存儲解決方案。 mongoD ...
  • 這學期還是下定決心打算考研了,現在已經定好學校和專業。因為是跨考,所以打算早點開始專業課。我考的那個學校電腦技術專業需要考《數據結構》、《操作系統》、《電腦網路》。個人認為,數據結構和操作系統是很基礎的東西,如果學好了對於學其他東西都會有很大幫助,所以我打算從數據結構開始。因為C語言剛開始一直是 ...
  • 描述 佈置宴席最微妙的事情,就是給前來參宴的各位賓客安排座位。無論如何,總不能把兩個死對頭排到同一張宴會桌旁!這個艱巨任務現在就交給你,對任何一對客人,請編寫程式告訴主人他們是否能被安排同席。 佈置宴席最微妙的事情,就是給前來參宴的各位賓客安排座位。無論如何,總不能把兩個死對頭排到同一張宴會桌旁!這 ...
  • 傳送門(bzoj) 傳送門(luogu) 題目: Description 小西有一條很長的彩帶,彩帶上掛著各式各樣的彩珠。已知彩珠有N個,分為K種。簡單的說,可以將彩帶考慮為x軸,每一個彩珠有一個對應的坐標(即位置)。某些坐標上可以沒有彩珠,但多個彩珠也可以出現在同一個位置上。 小布生日快到了,於是 ...
  • OOP的好處,關鍵的OOP概念,構造函數和析構函數,靜態類成員,instanceof關鍵字,輔助函數,自動載入函數 ...
  • 原文發佈在特克斯博客www.susmote.com 之前給大家講了關於python的背景知識,還有Python的優點和缺點,相信通過之前的介紹很多人已經清楚自己到底要不要選擇學習Python,如果已經很有興趣了,那麼你就可以自己查看一些有關Python的官方文檔,或是買本書啃啃,如果你暫時還沒什麼興 ...
  • .NET Core是一個開源通用的開發框架,具有跨平臺能力,我們在享受其性能飆升的同時,也面臨了一些問題。通過觀察 NetCore 程式的線上運行情況發現 ,負載高的情況下應用程式占用記憶體較大,本文將針對這個問題展開討論,對比分析不同GC工作模式下的.NetCore性能與記憶體管理的表現。通過查找資料 ...
  • 看圖: 這裡可以看到是二層嵌套!!使用C#如何實現?? 思路:使用list集合實現 → 建立類 → list集合 → 微軟的 Newtonsoft.Json (一款.NET中開源的Json序列化和反序列化) sonXMText類 using System; using System.Collecti ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...