The use of a Foreach loop is implemented with a IEnumerator interface, and IEnumerator implements an iterator that iterates over a collection ArrayList in foreach.
- Call Arraylis.getenumberator () to return a ienumberator reference.
- Invokes the MoveNext () method of the returned Enumberator interface.
- If MoveNext () returns True, a reference to the object is obtained using the current property of the Ienumberator interface for the Foreach loop.
- Repeat the first two steps, knowing that the MoveNext method returns false, at which time the loop stops.
Examples of implementations of iterators:
classProgram { Public Static voidMain (string[] args) { foreach(stringStrinchSimpleList ()) {Console.WriteLine (str); } console.readkey (); } Public StaticIEnumerable SimpleList () {yield return "1"; yield return "2"; yield return "3"; } }
This allows us to implement one of the simplest iterators. The result is:
Here is a more complicated example of using an iterator to implement the return prime:
Public Static void Main (string[] args) { new Primes (2); foreach (long in primesfrom2to1000) { Console.Write ("{0}", I); } }
Public classPrimes {Private Longmin; Private LongMax; PublicPrimes (): This(2, $) { } PublicPrimes (LongMinimumLongmaximum) { if(Minimum <2) {min=2; } Else{min=minimum; } Max=maximum; } PublicSystem.Collections.IEnumerator GetEnumerator ()//return type is an iterator { for(Longpossibleprime = min; Possibleprime <= Max; possibleprime++) { BOOLIsPrime =true; for(LongPossiblefactor =2; Possiblefactor <= (Long) Math.floor (Math.sqrt (possibleprime)); possiblefactor++) { LongRemainderafterdivsion = possibleprime%Possiblefactor; if(Remainderafterdivsion = =0) {IsPrime=false; Break; } } if(isprime) {yield returnPossibleprime;//for the prime number, the return } } } }
The result is:
There are two types of iterators returned: Ienumberable and IEnumerator.
- If you want to iterate over a class, you can use GetEnumerator (), whose return type is IEnumerator.
- If you want to iterate over a class member, such as a method, use IEnumerable.
. NET-based iterators