Here we only describe non-generic iterators, which are similar.
Code 1:
Public class Cars
{
Private int [] intArr = {1, 2, 3, 4, 5, 6, 7 };
/// <Summary>
/// Name iterator
/// </Summary>
/// <Param name = "isReverse"> whether to perform reverse iteration </param>
/// <Returns> </returns>
Public IEnumerable SortEnum (bool isReverse)
{
If (! IsReverse)
{
For (int I = 0; I <intArr. Length; I ++)
{
Yield return intArr [I];
}
}
Else
{
For (int I = intArr. Length-1; I> = 0; I --)
{
Yield return intArr [I];
}
}
} // Fun
} // Clas
Then you can iterate on the class. The Code is as follows:
Cars c = new Cars(); foreach (var item in c.SortEnum(true)) { Console.WriteLine(item); }
In fact, during compilation, the compiler generates an internal class for this class, which implements the IEnumerable and IEnumerator interfaces.
Code 2:
Method for returning IEnumerator
Public class Cars
{
Public IEnumerator GetEnumerator ()
{
Yield return "1 ";
Yield return "2 ";
Yield return "3 ";
} // Fun
} // Clas
The sample code is as follows:
// Note that c2 does not need to call the method Cars c2 = new Cars (); foreach (var item in c2) {Console. WriteLine (item );}
The compiler also generates an internal class for this class, which implements the IEnumerator interface.
It can be seen that if you want to use the yield syntax to traverse its subelements using foreach for a type, you only need to satisfy one of the following two conditions:
1) there is a method to return IEnumerable, which is an internal yield statement.
2) there is a public IEnumerator GetEnumerator () signature method. The yield statement is used internally.
The reason why the above Code can be written is that the compiler helps us implement the conditions we do not have to implement manually.