I. Understanding of several basic concepts
Question one: Why arrays can use the foreach output elements
A: An array is an enumerable type that implements an enumerator (enumerator) object, the enumerator knows the order of the elements and tracks their positions, and then returns the current item of the request
Question two: Can I traverse the elements without foreach?
Question three: What is an enumerable class
A: An enumerable class is a class that implements the IEnumerable interface; The IEnumerable interface has only one member GetEnumerator method, which returns an enumerator for the object
Question four: What is an enumerator
A: The enumerator that implements the IEnumerator interface contains three function members: Current,movenext,reset
Current is a read-only property that returns a reference to type object;
MoveNext is the method of advancing the enumerator position to the next item of the collection, which returns a Boolean value indicating whether the new position is valid or has exceeded the tail of the sequence;
Reset is the method of resetting the position to its original state;
Second, the following code shows a complete example of an enumerable class
1 namespaceConsoleApplication42{3 // <summary>4 /// Customize an Enumeration object5 // </summary>6 classColorenumerator:ienumerator7{8 Private string[] _colors;9 Private int_position =-1;Ten One PublicColorenumerator (string[] arr) A{ -_colors = arr; - for(inti = 0; I < arr. Length; i++) the{ -_colors[i] = Arr[i]; -} -} + Public ObjectCurrent -{ + Get A{ at if(_position = =-1) -{ - Throw NewInvalidOperationException (); -} - if(_position >= _colors. Length) -{ in Throw NewInvalidOperationException (); -} to return_colors[_position]; +} -} the * Public BOOLMoveNext () ${Panax Notoginseng if(_position < _colors. LENGTH-1) -{ the_position++; + return true; A} the Else +{ - return false; $} $} - - Public voidReset () the{ -_position =-1;Wuyi} the} - Wu // <summary> - /// Create an enumeration class that implements the IEnumerable interface About // </summary> $ classSpectrum:ienumerable -{ - Private string[] Colors = {"Red", "Yellow", "Blue" }; - PublicIEnumerator GetEnumerator () A{ + return NewColorenumerator (Colors); the} -} $ the classProgram the{ the Static voidMain (string[] args) the{ -Spectrum Spectrum =NewSpectrum (); in foreach(stringColorinchSpectrum the{ theConsole.WriteLine (color); About} theConsole.readkey (); the} the} +} - View Code
C. Generic Enumeration interface
The GetEnumerator method of the Ienumerable<t> interface returns an instance of the enumeration class that implements the Ienumerator<t>;
The class implementing the Ienumerator<t> implements the current property, which returns objects of the actual type, not references to the object base class;
So implementations of non-generic interfaces are not type-safe, because they also need to be converted to actual types.
Iv. iterators 1. Using iterators to create enumerators
1 namespaceConsoleApplication52{3 classMyClass4{5 // <summary>6 /// get an iterator7 // </summary>8 // <returns></returns>9 Publicienumerator<string> GetEnumerator ()Ten{ One returnColorenumerator (); A} - // <summary> - /// iterators the // </summary> - // <returns></returns> - Publicienumerator<string> Colorenumerator () -{ +Yieldreturn"Red"; -Yieldreturn"Yellow"; +Yieldreturn"Blue"; A} at} - classProgram -{ - Static voidMain (string[] args) -{ -MyClass MC =NewMyClass (); in foreach(stringColorinchMc -{ toConsole.WriteLine (color); +} -Console.readkey (); the} *} $} View Code2. Using iterators to create enum types
1 namespaceConsoleApplication62{3 classMyClass4{5 Publicienumerator<string> GetEnumerator ()6{7 //Get enumerable types8ienumerable<string> enumerable = colorenumerable ();9 //Get enumeratorTen returnColorenumerable (). GetEnumerator (); One} A - Publicienumerable<string> colorenumerable () -{ theYieldreturn"Red"; -Yieldreturn"Yellow"; -Yieldreturn"Blue"; -} +} - classProgram +{ A Static voidMain (string[] args) at{ -MyClass MC =NewMyClass (); - //Use class object - foreach(stringColorinchOck -{ -Console.WriteLine (color); in} -Console.WriteLine ("-----------------------"); to //methods for using class enumerators + foreach(stringColorinchMc. Colorenumerable ()) -{ theConsole.WriteLine (color); *} $Console.readkey ();Panax Notoginseng} -} the} View Code3. Generate multiple iterative types
1 namespaceConsoleApplication72{3 classMyClass4{5 Private string[] Colors = {"Red", "Yellow", "Blue" };6 //Order7 Publicienumerable<string> Colororder ()8{9 for(inti = 0; i < colors.length; i++)Ten{ OneYieldreturnColors[i]; A} -} - //Reverse Order the Publicienumerable<string> colorreversed () -{ - for(inti = colors.length-1; I >= 0; i--) -{ +YieldreturnColors[i]; -} +} A} at classProgram -{ - Static voidMain (string[] args) -{ -MyClass MC =NewMyClass (); - foreach(stringColorinchMc. Colororder ()) in{ -Console.WriteLine (color); to} +Console.WriteLine ("------------------"); - foreach(stringColorinchMc. Colorreversed ()) the{ *Console.WriteLine (color); $}Panax NotoginsengConsole.readkey (); -} the} +} A View Code
C # Knowledge points-enumerators and iterators