The most common method to create an iterator isIenumerableInterface implementationGetenumeratorMethod
For example, the implementation of the output A-Z:
Public Class A {public system. collections. ienumerator getenumerator () {for (INT I = 65; I <= 90; I ++) {yield return (char) I ;}}}
The call method is as follows:GetenumeratorThe method makes the type an enumerated type and allows the use of foreach statements.
Static void main (string [] ARGs) {foreach (char I in new A () {console. Write (I );}}
Foreach statement callInstance. getenumerator ()The returned enumerated values are used for loop access.
Running result diagram:
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 iteratorSampleiteratorImplementationIenumerableInterface:
Public Class B {public system. collections. ienumerable sampleiterator (INT start, int end) {for (INT I = start; I <= end; I ++) {yield return I ;}}}
The calling method of the named iterator is as follows:
Static void main (string [] ARGs) {foreach (int I in new B (). sampleiterator (1, 10) {console. Write (I );}}
The running result is shown as follows:
Multiple yield statements can be used in the same iterator, as shown in the following example:
Public class c {public system. Collections. ienumerator getenumerator () {yield return "Bo"; yield return ""; yield return ""; yield return ". ";}}
Then you can use the following foreach statement to output the result:
Static void main (string [] ARGs) {foreach (string s in new C () {console. Write (s );}}
Running result:
The materials are from msdn, which records my learning path. If you forget it, you can watch it later and record your own growth!
Copyright. For more information, see the source!
All great actions and thoughts have a negligible start. I am learning the knowledge and hope to succeed! Don't give up on me. I 'd like to make friends all over the world!