[原譯]實現IEnumerable介面&理解yield關鍵字

來源:互聯網
上載者:User

著作權聲明:本文由http://leaver.me 翻譯,歡迎轉載分享。請尊重作者勞動,轉載時保留該聲明和作者部落格連結,謝謝!

本文討論題目的內容。然後討論IEnumerable介面如何使得foreach語句可以使用。之後會展示如果實現自訂的集合類,該集合類實現了IEnumerable介面。Yield關鍵字和遍曆集合後面也討論。

背景

一使用集合。就發現遍曆集合就跟著來了。遍曆集合最好的方式是實現迭代器模式-Understanding and Implementing the Iterator Pattern in C# and C++(這篇文章我過幾天翻譯一下) ,C#提供foreach來以一種優雅的方式遍曆

只要集合實現了IEnumerable 介面就可以用foreach來遍曆。

使用代碼

首先先看一下內建的集合類如何使用foreach來遍曆的。ArrayList實現了IEnumerable 介面。我們看一下

// 看一下實現了IEnumerable 介面的集合如何遍曆ArrayList list = new ArrayList();list.Add("1");list.Add(2);list.Add("3");list.Add('4');foreach (object s in list){    Console.WriteLine(s);}

 

 

遍曆泛型集合類

Arraylist 是一個通用集合類,遍曆泛型集合類也可以。因為這些泛型集合類實現了IEnumerable<T>介面,看一下吧。

// 遍曆實現了IEnumerable<T>介面的泛型類List<string> listOfStrings = new List<string>();listOfStrings.Add("one");listOfStrings.Add("two");listOfStrings.Add("three");listOfStrings.Add("four");foreach (string s in listOfStrings){    Console.WriteLine(s);} 

發現了吧。我們自訂的集合類或是泛型集合類應該實現IEnumerable和IEnumerable<T>介面。這樣就可以遍曆了。

 

理解yield關鍵字

在寫個實現介面的例子之前,先理解一下yield關鍵字,yield會記錄集合位置。當從一個函數返回一個值的時候,yield可以用。

如下的普通的方法。不論調用多少次,都只會返回一個return

static int SimpleReturn(){    return 1;    return 2;    return 3;}static void Main(string[] args){    // 看看    Console.WriteLine(SimpleReturn());    Console.WriteLine(SimpleReturn());    Console.WriteLine(SimpleReturn());    Console.WriteLine(SimpleReturn());}

 

 

原因就是普通的return語句不保留函數的返回狀態。每一次都是新的調用。然後返回第一個值。

但是使用下面的語句替換後就不一樣。當函數第二次調用的時候。會從上次返回的地方繼續調用

static IEnumerable<int> YieldReturn(){    yield return 1;    yield return 2;    yield return 3;}static void Main(string[] args){    // 看看yield return的效果    foreach (int i in YieldReturn())    {        Console.WriteLine(i);    }}

 

顯然返回1,2,3,唯一要注意的就是函數需要返回IEnumerable。,然後通過foreach調用。

在自訂的集合類裡實現Ienumerable介面

現在如果我們在我們的自訂集合裡定義一個方法。來迭代所有元素。然後通過使用yield返回。我們就可以成功了。

好。我們定義MyArrayList 類,實現IEnumerable 介面,該介面就會強制我們實現GetEnumerator 函數。這裡我們就要使用yield了。

class MyArrayList : IEnumerable{    object[] m_Items = null;    int freeIndex = 0;    public MyArrayList()    {        // 對了方便我直接用數組了,其實應該用鏈表       m_Items = new object[100];    }    public void Add(object item)    {        // 考慮添加元素的時候        m_Items[freeIndex] = item;        freeIndex++;    }    // IEnumerable 函數    public IEnumerator GetEnumerator()   {       foreach (object o in m_Items)        {           // 檢查是否到了末尾。數組的話。。。沒寫好            if(o == null)            {                break;            }            // 返回當前元素。然後前進一步            yield return o;        }    }}

 

 

 

之後你就可以用foreach遍曆了。

static void Main(string[] args){    //看看調用部分    MyArrayList myList = new MyArrayList();    myList.Add("1");    myList.Add(2);    myList.Add("3");    myList.Add('4');    foreach (object s in myList)    {        Console.WriteLine(s);    }}

 

 

這個類啊。沒寫好。也不完整。只要是讓你理解。。類比一下而已。

自訂泛型類裡實現Ienumerable<T>介面

class MyList<T> : IEnumerable<T>{    T[] m_Items = null;    int freeIndex = 0;    public MyList()    {        // 為了方便。使用數組        m_Items = new T[100];    }    public void Add(T item)    {        //添加元素        m_Items[freeIndex] = item;        freeIndex++;    }    #region IEnumerable<T> Members     public IEnumerator<T> GetEnumerator()    {        foreach (T t in m_Items)        {            //檢查是否到了末尾。數組的話。。。沒寫好            if (t == null) // 如果T不是一個可空類型。就中斷            {                break;            }            // 返回當前元素,然後前進一步            yield return t;        }    }    #endregion     #region IEnumerable Members    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()    {        // 此處調用泛型版本        return this.GetEnumerator();    }    #endregion}

 

 

之後就可以使用foreach了。

static void Main(string[] args){    // 使用樣本    MyList<string> myListOfStrings = new MyList<string>();    myListOfStrings.Add("one");    myListOfStrings.Add("two");    myListOfStrings.Add("three");    myListOfStrings.Add("four");    foreach (string s in myListOfStrings)    {        Console.WriteLine(s);    }}

 

 原始碼下載

EnumerableDemo.7z

原文地址: A-Beginners-Tutorial-on-Implementing-IEnumerable-I

著作權聲明:本文由http://leaver.me 翻譯,歡迎轉載分享。請尊重作者勞動,轉載時保留該聲明和作者部落格連結,謝謝!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.