Method for using the Foreach statement without defining the IEnumerable and IEnumrator interface

xiaoxiao2021-03-06  69

Everyone knows that the Foreach statement works on the interface that defines the Ienumerable interface. such as:

String [] SARR = New String [10];

FOREACH (String S in Sarr)

Console.WriteLine (s);

If you don't define the Ienumerable interface, you will have a compilation error. But this limit is not absolute. According to the C # language specification, as long as the following conditions can be met, even if the IenumRable / Ienumrator interface can also be used.

1. Assume that the expression has a genumrator () method.

2. The object returned by the getEnumerator () method defines the method of all IENUMERATOR interface definitions, namely Public Interface IEnumerator

{// Methods

Bool movenext ();

Void reset ();

// Properties

Object current {get;}

}

"Access to the FOREACH Simplified Text File" (Read) The LineReader introduced in the text does not declares the IENUMERABLE / IENUMRATOR interface, but it works in the foreach statement. Another feature of LineReader is the getNumerator () method:

Public LineReader geteNumerator ()

{

Return this;

}

Did not create a new object instance, but return itself, so you can save the overhead of creating an object, and simplify the program logic. The disadvantage is that a LineReader can only open an enumerator at the same time, open more than more than one Enumerator, the program is incorrect. But from the scene running from LineReader. We always follow the FOREACH (String Line in New LineReader) to use without opening two Enumerator, or in multithreading.

转载请注明原文地址:https://www.9cbs.com/read-121239.html

New Post(0)