The most common method to create an iterator is to implement the getenumerator method for the ienumerable interface, for example:
PublicSystem. Collections. ienumerator getenumerator ()
{
For(IntI = 0; I <10; I ++)
{
Yield ReturnI;
}
}
The existence of the getenumerator method makes the type an enumerated type and allows the use of foreach statements. If the above method is part of the class definition of listclass, you can use foreach for this class, as shown below:
Static VoidMain ()
{
Listclass listclass1 =NewListclass ();
Foreach(IntIInListclass1)
{
System. Console. writeline (I );
}
}
The foreach statement calls listclass. getenumerator () and uses the returned enumerated number to cyclically access the value.
You can also use the named iterator to support cyclically accessing the same data set in different ways. For example, you can provide an iterator for returning elements in ascending order, and another iterator for returning elements in descending order. The iterator can also contain parameters to allow the client to control all or part of the iteration behavior. The following iterator uses the named iterator sampleiterator to implement the ienumerable interface:
// Implementing the enumerable Pattern
PublicSystem. Collections. ienumerable sampleiterator (IntStart,IntEnd)
{
For(IntI = start; I <= end; I ++)
{
Yield ReturnI;
}
}
The calling method of the named iterator is as follows:
Listclass test =NewListclass ();
Foreach(IntNInTest. sampleiterator (1, 10 ))
{
System. Console. writeline (N );
}
Multiple yield statements can be used in the same iterator, as shown in the following example:
PublicSystem. Collections. ienumerator getenumerator ()
{
yield return " with an iterator, ";
yield return " more than one ";
yield return " value can be returned ";
Yield Return ".";
}
Then you can use the following foreach statement to output the result:
Foreach(StringElementIn NewTestclass ())
{
System. Console. Write (element );
}
This example displays the following text:
With an iterator, more than one value can be returned.
in each subsequent iteration of the foreach loop (or for ienumerator. in movenext), the next iterator Code starts after the previous yield statement, continue the next statement until it reaches the end of The iterator body or encounters the yield break statement.