C#編程:使用迭代器
創(chuàng)建迭代器最常用的方法是對 IEnumerable 接口實現(xiàn) GetEnumerator 方法,例如:
- public System.Collections.IEnumerator GetEnumerator()
- {
- for (int i = 0; i < max; 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 語句調(diào)用 ListClass.GetEnumerator() 并使用返回的枚舉數(shù)來循環(huán)訪問值。有關(guān)如何創(chuàng)建返回 IEnumerator 接口的泛型迭代器的示例,請參見 如何:為泛型列表創(chuàng)建迭代器塊(C# 編程指南)。
還可以使用命名的迭代器以支持通過不同的方式循環(huán)訪問同一數(shù)據(jù)集合。例如,您可以提供一個按升序返回元素的迭代器,而提供按降序返回元素的另一個迭代器。迭代器還可以帶有參數(shù),以便允許客戶端控制全部或部分迭代行為。下面的迭代器使用命名的迭代器 SampleIterator 實現(xiàn) IEnumerable 接口:
- // Implementing the enumerable pattern
- public System.Collections.IEnumerable SampleIterator(int start, int end)
- {
- for (int i = start; i < = end; i++)
- {
- yield return i;
- }
- }
命名的迭代器的調(diào)用方法如下:
- 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 語句輸出結(jié)果:
- foreach (string element in new TestClass())
- {
- System.Console.Write(element);
- }
此示例顯示以下文本:
- With an iterator, more than one value can be returned.
在 foreach 循環(huán)的每次后續(xù)迭代(或?qū)?IEnumerator.MoveNext 的直接調(diào)用)中,下一個迭代器代碼體將從前一個 yield 語句之后開始,并繼續(xù)下一個語句直至到達迭代器體的結(jié)尾或遇到 yield break 語句。
【編輯推薦】