.Net 2.0里有一个有用的新功能:迭代器
迭代器(C# 編程指南)?
迭代器是 C# 2.0 中的新功能。迭代器是方法、get 訪問器或運算符,它使您能夠在類或結(jié)構(gòu)中支持 foreach 迭代,而不必實現(xiàn)整個 IEnumerable 接口。您只需提供一個迭代器,即可遍歷類中的數(shù)據(jù)結(jié)構(gòu)。當(dāng)編譯器檢測到迭代器時,它將自動生成 IEnumerable 或 IEnumerable 接口的 Current、MoveNext 和 Dispose 方法。
迭代器概述
-
迭代器是可以返回相同類型的值的有序序列的一段代碼。
-
迭代器可用作方法、運算符或 get 訪問器的代碼體。
-
迭代器代碼使用 yield return 語句依次返回每個元素。yield break 將終止迭代。有關(guān)更多信息,請參見 yield。
-
可以在類中實現(xiàn)多個迭代器。每個迭代器都必須像任何類成員一樣有唯一的名稱,并且可以在 foreach 語句中被客戶端代碼調(diào)用,如下所示:foreach(int x in SampleClass.Iterator2){}
-
迭代器的返回類型必須為 IEnumerable、IEnumerator、IEnumerable 或 IEnumerator。
yield 關(guān)鍵字用于指定返回的值。到達 yield return 語句時,會保存當(dāng)前位置。下次調(diào)用迭代器時將從此位置重新開始執(zhí)行。
迭代器對集合類特別有用,它提供一種簡單的方法來迭代不常用的數(shù)據(jù)結(jié)構(gòu)(如二進制樹)。
備注
yield 語句只能出現(xiàn)在 iterator 塊中,該塊可用作方法、運算符或訪問器的體。這類方法、運算符或訪問器的體受以下約束的控制:
-
不允許不安全塊。
-
方法、運算符或訪問器的參數(shù)不能是 ref 或 out。
yield 語句不能出現(xiàn)在匿名方法中。有關(guān)更多信息,請參見匿名方法(C# 編程指南)。
當(dāng)和 expression 一起使用時,yield return 語句不能出現(xiàn)在 catch 塊中或含有一個或多個 catch 子句的 try 塊中。示例
說明
在本示例中,DaysOfTheWeek 類是將一周中的各天作為字符串進行存儲的簡單集合類。foreach 循環(huán)每迭代一次,都返回集合中的下一個字符串。
C#
public?class?DaysOfTheWeek?:?System.Collections.IEnumerable
{
????string[]?m_Days?=?{?"Sun",?"Mon",?"Tue",?"Wed",?"Thr",?"Fri",?"Sat"?};
????public?System.Collections.IEnumerator?GetEnumerator()
????{
????????for?(int?i?=?0;?i?<?m_Days.Length;?i++)
????????{
????????????yield?return?m_Days[i];
????????}
????}
}
class?TestDaysOfTheWeek
{
????static?void?Main()
????{
????????//?Create?an?instance?of?the?collection?class
????????DaysOfTheWeek?week?=?new?DaysOfTheWeek();
????????//?Iterate?with?foreach
????????foreach?(string?day?in?week)
????????{
????????????System.Console.Write(day?+?"?");
????????}
????}
}
輸出: Sun?Mon?Tue?Wed?Thr?Fri?Sat
在下面的示例中,迭代器塊(這里是方法 Power(int number, int power))中使用了 yield 語句。當(dāng)調(diào)用 Power 方法時,它返回一個包含數(shù)字冪的可枚舉對象。注意 Power 方法的返回類型是 IEnumerable(一種迭代器接口類型)。
//?yield-example.cs
using?System;
using?System.Collections;
public?class?List
{
????public?static?IEnumerable?Power(int?number,?int?exponent)
????{
????????int?counter?=?0;
????????int?result?=?1;
????????while?(counter++?<?exponent)
????????{
????????????result?=?result?*?number;
????????????yield?return?result;
????????}
????}
????static?void?Main()
????{
????????//?Display?powers?of?2?up?to?the?exponent?8:
????????foreach?(int?i?in?Power(2,?8))
????????{
????????????Console.Write("{0}?",?i);
????????}
????}
} 輸出:
2?4?8?16?32?64?128?256?
轉(zhuǎn)載于:https://www.cnblogs.com/Sandheart/archive/2006/11/13/559063.html
總結(jié)
以上是生活随笔為你收集整理的.Net 2.0里有一个有用的新功能:迭代器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 充电器国家标准重大更新!行业要洗牌了
- 下一篇: C#桌面时钟