拋磚引玉:
static void Main(string[] args){ int[] array = new int[] { 5,4,3,2,1}; foreach (int i in array) Console.WriteLine("Number:"+i); Console.ReadKey(); }/** * -------------執行結果------------- * Number:5 * Number:4 * Number:3 * Number:2 * Number:1 * -------------執行結果------------- */
問題:為什麼使用foreach可以遍曆出數組中的所有元素呢?
原因:數組是可枚舉類型,它可以按需提供枚舉數,枚舉數可以依次返回請求的數組的元素。而foreach結構被設計用來和可枚舉類型一起使用,只要給foreach的遍曆對象是可枚舉類型,則她就會執行如下行為:
- 通過調用GetEnumerator方法擷取對象(如:數組)的枚舉數(即數組中的元素值)
- 從枚舉數中請求每一項並把她作為迭代遍曆
因為數組是可枚舉類型,所以我就使用使用IEnumerator介面來實現枚舉數以模仿foreach的迴圈遍曆
實現代碼如下:
static void Main(string[] args){ int[] array = new int[] { 5,4,3,2,1}; IEnumerator ie = array.GetEnumerator();//擷取枚舉數 while (ie.MoveNext())//移動下一項 { //最初,枚舉數定位在集合中第一個元素前,在此位置上,Current 屬性未定義 //因此,在讀取 Current 的值之前,必須調用 MoveNext 方法將枚舉數提前到集合的第一個元素 int i = (int)ie.Current;//擷取當前項 Console.WriteLine("Number:" + i); } } /** * -------------執行結果------------- * Number:5 * Number:4 * Number:3 * Number:2 * Number:1 * -------------執行結果------------- */
實現IEnumerable 和 IEnumerator 介面
以下樣本示範如何?自訂集合的IEnumerable 和 IEnumerator 介面,在此樣本中,沒有顯式調用這些介面的成員,但實現了它們,以便支援使用 foreach逐一查看該集合
要點:
- 顯示實現IEnumerable介面的GetEnumerator成員函數
- 顯示實現IEnumerator介面的Current,Reset(),MoveNext()
:
using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication1{ // 實現IEnumerator介面 public class PersonIEnumerator : IEnumerator { string[] Person; int position = -1; public PersonIEnumerator(string[] thePersons) { Person = new string[thePersons.Length]; for (int i = 0; i < thePersons.Length; i++) { Person[i] = thePersons[i]; } } //IEnumerator介面的特性1 public object Current { get { return Person[position]; } } //IEnumerator介面的特性2 public bool MoveNext() { if (position < Person.Length - 1) { position++; return true; } else return false; } //IEnumerator介面的特性3 public void Reset() { position = -1; } } //實現IEnumerable介面 public class MyPersons : IEnumerable { string[] strArr = new string[] { "周星馳", "莫言", "碧咸", "林志穎" }; //返回IEnumerator類型的對象 public IEnumerator GetEnumerator() { return new PersonIEnumerator(strArr); } } class Program { static void Main(string[] args) { MyPersons mp = new MyPersons(); foreach (string name in mp) { Console.WriteLine("{0}", name); } Console.ReadKey(); } } /** * -------------執行結果------------- * 周星馳 * 莫言 * 碧咸 * 林志穎 * -------------執行結果------------- */}
註:C# 語言的 foreach 語句隱藏了枚舉數的複雜性。因此,建議使用 foreach,而不直接操作枚舉數
原創文章,轉載請註明出處:http://www.cnblogs.com/hongfei