/*文法:(C#)*/ [ComVisibleAttribute(true)] [GuidAttribute("496B0ABF-CDEE-11d3-88E8-00902754C43A")] public interface IEnumerator
備注:
/* IEnumerator 是所有非泛型枚舉數的基接口。 C# 語言的 foreach 語句(在 Visual Basic 中為 for each)隐藏了枚舉數的複雜性。是以,建議 foreach,而不直接操作枚舉數。枚舉數可用于讀取集合中的資料,但不能用于修改基礎集。 最初,枚舉數定位在集合中第一個元素前。Reset 方法還會将枚舉數傳回到此位置。在此位置,調用 Current 屬性會引發異常。是以,在讀取 Current 的值之前,必須調用MoveNext 方法将枚舉數提前到集合的第一個元素。在調用 MoveNext 或 Reset 之前,Current 傳回同一對象。MoveNext 将 Current 設定為下一個元素。 如果 MoveNext 越過集合的末尾,則枚舉數将被放置在此集合中最後一個元素的後面,而且 MoveNext 傳回 false。當枚舉數位于此位置時,對 MoveNext 的後續調用也傳回 false。如果最後一次調用 MoveNext 傳回 false,則調用 Current 會引發異常。若要再次将 Current 設定為集合的第一個元素,可以調用 Reset,然後再調用MoveNext。 隻要集合保持不變,枚舉數就保持有效。如果對集合進行了更改(如添加、修改或删除元素),則枚舉數将失效且不可恢複,并且下一次對 MoveNext 或 Reset 的調用将引發InvalidOperationException。如果在 MoveNext 和 Current 之間修改集合,那麼即使枚舉數已經無效,Current 也将傳回它所設定成的元素。 枚舉數沒有對集合的獨占通路權;是以,枚舉通過集合在本質上不是一個線程安全的過程。即使一個集合已進行同步,其他線程仍可以修改該集合,這将導緻枚舉數引發異常。若要在枚舉過程中保證線程安全,可以在整個枚舉過程中鎖定集合,或者捕捉由于其他線程進行的更改而引發的異常。 */
樣例:
using System; using System.Collections; //person類 public class Person { public Person(string fName, string lName) { this.firstName = fName; this.lastName = lName; } public string firstName; public string lastName; } //People類,實作IEnumerable public class People : IEnumerable { private Person[] _people; public People(Person[] pArray) { _people = new Person[pArray.Length]; for (int i = 0; i < pArray.Length; i++) { _people[i] = pArray[i]; } } public IEnumerator GetEnumerator() { return new PeopleEnum(_people); } } //實作IEnumerator public class PeopleEnum : IEnumerator { public Person[] _people; // Enumerators are positioned before the first element // until the first MoveNext() call. int position = -1; public PeopleEnum(Person[] list) { _people = list; } public bool MoveNext() { position++; return (position < _people.Length); } public void Reset() { position = -1; } public object Current { get { try { return _people[position]; }catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } } //app class App { static void Main() { Person[] peopleArray = new Person[3] { new Person("John", "Smith"), new Person("Jim", "Johnson"), new Person("Sue", "Rabon"), }; People peopleList = new People(peopleArray); foreach (Person p in peopleList) Console.WriteLine(p.firstName + " " + p.lastName); } } /* This code produces output similar to the following: * * John Smith * Jim Johnson * Sue Rabon * */