C#中如何使用迭代器

來源:互聯網
上載者:User

建立迭代器最常用的方法是對 IEnumerable 介面實現 GetEnumerator 方法,例如:

public System.Collections.IEnumerator GetEnumerator()
{
    for (int i = 0; i < 10; i++)
    {
        yield return i;
    }
}

GetEnumerator 方法的存在使得類型成為可枚舉的類型,並允許使用 foreach 語句。如果上面的方法是 ListClass 的類定義的一部分,則可以對該類使用 foreach,如下所示:

static void Main()
{
    ListClass listClass1 = new ListClass();
 
    foreach (int i in listClass1)
    {
        System.Console.WriteLine(i);
    }
}

foreach 語句調用 ListClass.GetEnumerator() 並使用返回的枚舉數來逐一查看值。

還可以使用命名的迭代器以支援通過不同的方式逐一查看同一資料集合。例如,您可以提供一個按升序返回元素的迭代器,而提供按降序返回元素的另一個迭代器。迭代器還可以帶有參數,以便允許用戶端控制全部或部分迭代行為。下面的迭代器使用命名的迭代器 SampleIterator 實現 IEnumerable 介面:

// Implementing the enumerable pattern
public System.Collections.IEnumerable SampleIterator(int start, int end)
{
    for (int i = start; i <= end; i++)
    {
        yield return i;
    }
}

命名的迭代器的調用方法如下:

ListClass test = new ListClass();
foreach (int n in test.SampleIterator(1, 10))
{
    System.Console.WriteLine(n);
}

可以在同一個迭代器中使用多個 yield 語句,如下面的樣本所示:

public System.Collections.IEnumerator GetEnumerator()
{
    yield return "With an iterator, ";
    yield return "more than one ";
    yield return "value can be returned";
    yield return ".";
}

然後可以使用下面的 foreach 語句輸出結果:

foreach (string element in new TestClass())
{
    System.Console.Write(element);
}

此樣本顯示以下文本:

With an iterator, more than one value can be returned.

在 foreach 迴圈的每次後續迭代(或對 IEnumerator.MoveNext 的直接調用)中,下一個迭代器代碼體將從前一個 yield 語句之後開始,並繼續下一個語句直至到達迭代器體的結尾或遇到 yield break 語句。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.