We often IEnumerable, but ignore IEnumerator. Simply put, IEnumerable is a collection that can be iterated through, and IEnumerator implements a loop traversal.
The interfaces are:
public interface IEnumerator
{
BOOL MoveNext ();
Object Current{get;}
void Reset ();
}
public interface IEnumerable
{
IEnumerator GetEnumerator ();
}
To perform such a simple console program.
Class Program
{
static void Main (string[] args)
{
IEnumerable<string> list = new List<string>() {" Hello "," World "};
foreach (var item in list)
{
Console.WriteLine (item);
}
Console.readkey ();
}
}
In Solution Explorer, right-click the console project and tap Open file in File Explorer.
Tap the bin and then click the Debug folder.
Copy the current file directory.
Open the developer command prompt.
Because the application file is in the F drive, enter the following:
Directed to the directory you just assigned, enter the following:
To view the list in the current directory, enter the following:
Use. NET ILDASM decompile the application file and enter it into a txt text. Enter as follows:
Open a 1.txt file and enter the following:
The 1.txt file is opened with the associated IL code as follows:
As can be seen, foreach is also a syntactic sugar, which is actually a method of invoking IEnumerable's IEnumerator when using a foreach loop.
So, for foreach, you can change the way you do it:
Class Program
{
static void Main (string[] args)
{
IEnumerable<string> list = new List<string>() {" Hello "," World "};
IEnumerator it = list. GetEnumerator ();
while (it. MoveNext ())
{
Console.WriteLine (it. Current);
}
Console.readkey ();
}
}
IEnumerable is a collection, IEnumerator is a collection of iterators