.Net索引器和迭代器
.Net索引器
- 索引器
索引器允許類或結(jié)構(gòu)的實例按照與數(shù)組相同的方式進(jìn)行索引。索引器類似于屬性,不同之處在于它們的訪問器采用參數(shù)。
- 特性
- 索引器使得對象可按照與數(shù)組相似的方法進(jìn)行索引。
- get 訪問器返回值。set 訪問器分配值。
- this 關(guān)鍵字用于定義索引器。
- value 關(guān)鍵字用于定義由 set 索引器分配的值。
- 索引器不必根據(jù)整數(shù)值進(jìn)行索引,由您決定如何定義特定的查找機制。
- 索引器可被重載。
- 索引器可以有多個形參,例如當(dāng)訪問二維數(shù)組時。
- 代碼示例
- class SampleCollection<T>
- {
- private T[] arr = new T[100];
- public T this[int i]
- {
- get
- {
- return arr[i];
- }
- set
- {
- arr[i] = value;
- }
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- SampleCollection<string> stringCollection = new SampleCollection<string>();
- stringCollection[0] = "Hello, World";
- System.Console.WriteLine(stringCollection[0]);
- }
- }
.Net迭代器
- 迭代器
您只需提供一個迭代器,即可遍歷類中的數(shù)據(jù)結(jié)構(gòu)。當(dāng)編譯器檢測到迭代器時,它將自動生成 IEnumerable 或 IEnumerable<T> 接口的 Current、MoveNext 和 Dispose 方法。
迭代器是可以返回相同類型的值的有序序列的一段代碼。
迭代器可用作方法、運算符或 get 訪問器的代碼體。
迭代器代碼使用 yield return 語句依次返回每個元素。yield break 將終止迭代。
可以在類中實現(xiàn)多個迭代器。每個迭代器都必須像任何類成員一樣有***的名稱,并且可以在 foreach 語句中被客戶端代碼調(diào)用,如下所示:foreach(int x in SampleClass.Iterator2){}
迭代器的返回類型必須為 IEnumerable、IEnumerator、IEnumerable<T> 或 IEnumerator<T>。
- 代碼示例
- 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()
- {
- DaysOfTheWeek week = new DaysOfTheWeek();
- foreach (string day in week)
- {
- System.Console.Write(day + " ");
- }
- }
- }
原文鏈接:http://www.cnblogs.com/liusuqi/archive/2013/06/05/3118268.html
http://www.cnblogs.com/liusuqi/archive/2013/06/06/3120390.html