enumerators and enumerable types we already know that using the foreach statement, you can iterate over the elements in the array. But why did you do it? The reason is that the array provides an object called an enumerator on demand. The enumerator can sequentially return the elements in the request array. The enumerator knows the order of the items and keeps track of where they are in the sequence, and then returns the current item of the request. The way to get an object enumerator is to call the object's GetEnumerator method. The type of implementation of the GetEnumerator method is called an enumerable type. An array is an enumerable type. The IEnumerator interface implements an enumerator for the IEnumerator interface that contains 3 function members: Current,movenext,reset.current is the property that returns the current position item in the sequence. It is a read-only property that returns a reference to type object, so any type can be returned. MoveNext is the way to advance the enumerator position to the next item in the collection. It returns a Boolean value that indicates whether the new position is valid or has exceeded the tail of the sequence. If the new location effectively returns true, the new location is invalid and returns false. The original position of the enumerator precedes the first item in the sequence, so MoveNext must be called before the first use of current. Reset is the method that resets the position to its original state. IEnumerable interface An enumerable class is a class that implements the IEnumerable interface, and the IEnumerable interface has only one member---GetEnumerator Method, he returns an enumerator for the object. usingSystem.Collections;classmyclass:ienumerable{ PublicIEnumerator getenumerator{...}//returns an object of type IEnumerator}usingSystem.Collections;//to add this line of codenamespaceconsoleapplication1{classProgram {Static voidMain (string[] args) { int[] Myarray = {Ten, One, A, -};//Create an array//System.Collections.IEnumerator ie = Myarray.getenumerator ();//or use this without the namespace above;IEnumerator ie =Myarray.getenumerator (); while(ie. MoveNext ()) {inti = (int) ie. Current; Console.WriteLine ("{0}", i); } console.read (); } }}Static voidMain (string[] args) { int[] Myarray = {Ten, One, A, -};//Create an array foreach(intIinchMyarray) Console.WriteLine ("{0}", i); Console.read (); The above code has the same effect as foreach;
Enumerators and enumerable types