foreach can traverse some data types. As can be seen from the figure, the data type being traversed must have the public method GetEnumerator.
When using foreach traversal, the var inference type is involved. If the generic version is not implemented at this time, it will always be the object type.
Foreach traversal can only read data, but cannot modify data. It can be detected through string. String is traversable, but the char that makes up it cannot be changed. (Only in this scenario).
foreach traverses only forward, reading one by one, similar to the Read method of DataReader that operates the database.
It can be seen from the above analysis that the IEnumerator method needs to be defined inside the class in order to be traversed. There are two solutions here.
Method 1, through yield
yield return expression; if the return value is IEnumerable
If the return value is IEnumerator
#You can use this to get the value of the person array in the above picture when traversing.
Method 2 By implementing the IEnumerable interface
IEunmerable includes the GetEunmetator method, and the return value is the type of IEnumerator.
At this time, another class is needed to inherit the IEnumerator interface, so that its subclass can be returned to achieve the purpose.
Implementation process:
1. You need to add a variable of type int to mark the position of the index. Use int position=-1 here.
2. Add the corresponding array variable to receive the passed array. The Curren attribute implemented here using string[] persion;
3. needs to return the data of the current index. return person[position];
4. To implement the MoveNext method, you need to add 1 to the pointer (index) and move forward. The return value is a bool type, which is used to determine whether the index has been operated.
5. Implement the Reset method, which is the reset method, and assign position to -1;
6. Add a constructor with parameters to receive the passed data.
3. List collection analysis
It can be seen from the reflection tool that the Add method of the List collection is to give the internal item Add a value, and this item is an array. Because it is generic, it is displayed as T.
That is, there is such a variable inside the collection to store the added data, just like the array defined above, so the List collection class is customized with the above
The classes are consistent. The above definition is just to demonstrate the process. Of course, due to business needs, you can implement and extend the above classes yourself, such as changing the static data
to the Add method to add and filter data. Logic, etc., can be expanded according to business needs.
The above is the detailed content of foreach example code in C#. For more information, please follow other related articles on the PHP Chinese website!