1. What are the enumerated types and enumerated numbers?
Enumerable type: implements the type of the GetEnumerator method, and returns the number of enumerations used for items.
Enumeration number: enumeration number is a class object that can return items in the Set in sequence. Generally, you can call the GetEnumerator method to retrieve enumeration objects of enumeration types.
Explains the relationship between enumerated types and enumerated numbers:
2. How is foreach statement implemented?
The foreach statement is designed for use with enumeration types. As long as its traversal object is of the enumerable type.
For example, the array performs the following actions to traverse the output.
1> call the GetEnumerator method to obtain the number of enumerated objects.
2> request each item from the enumerated number and use it as an iteration variable. The code can be read but cannot be changed.
For example:
// Method 1: Use the MoveNext method and Current attribute of the IEnumerator interface to simulate the array traversal Effect of foreach loop.
Class Program
{
Static voidMain (string [] args)
{
Int [] arr = {1, 2, 3, 4, 5}; // declare and initialize the array.
IEnumerator ie = arr. GetEnumerator (); // call the GetEnumerator method of the enumerated type to obtain the enumerated number object.
While (ie. MoveNext () // move the MoveNext method that calls the IEnumerator interface to the next one. Implements traversal of arrays.
{
Int I = (int) ie. Current; // call the Current method of the IEnumerator interface to obtain the Current item. Note that it returns the object type and requires forced conversion.
Console. WriteLine ("{0}", I );
}
Console. ReadKey ();
}
}
The program output result is:
// Method 2: Use foreach to traverse the array:
class Program
{
Static voidMain (string [] args)
{
Int [] arr = {1, 2, 3, 4, 5}; // declare and initialize the array.
Foreach (int item in arr) // use the foreach statement to traverse the array.
{
Console. WriteLine ("{0}", item );
}
Console. ReadKey ();
}
}
The program output result is the same as the above
Author's permanent Wheat