When I first came into contact with C #, I was IEnumerable, IEnumerator, ICollection , so I made a thorough understanding of their essential relationship.
When it comes to IEnumerable it is natural to think of IEnumerator,foreach and so on. They do have a lot of close relationships, and today I'll explain the relationship in detail, with only one abstract method in the IEnumerable interface.
GetEnumerator (), he returns an IEnumerator object that can access the Loop collection. The object is the true collection accessor. As long as it is available, foreach can iterate through the array or collection because only IEnumerator
In order to access each item in the collection, since IEnumerator is so magical, let's take a look at what it defines inside it, and then, by deserializing it, only define a current property, MoveNext and reset two methods,
Iterate through the array with foreach. As an example, if you declare a class Grad:
public class Grad { car[] Cararray = new Car[4]; Define an array of car types in garage cararray, in fact Cararray here is an array field //start with some car object public Gard () { //Array field assignment cararray[0] = new Car ("Rusty", +); CARARRAY[1] = new Car ("clunker", +); CARARRAY[2] = new Car ("Zippy", +); CARARRAY[3] = new Car ("Fred",); } }
Then you want to use the Foreach loop, sorry cannot be implemented, because the class does not have the GetEnumerator () method, there is no IEnumerator object, it is impossible to call the method MoveNext (), cannot call MoveNext, it is impossible to loop the
This method is defined by the IEnumerable interface that is hidden in the System.Collections namespace. Then someone asked: then why list can Ah! Because the list inherits the IEnumerable interface, the list can be used! ,
In summary, if a type supports a foreach traversal, the following conditions must be met:
Scenario 1: Let this class implement the IEnumerable interface
Scenario 2: This class has an instance method of public GetEnumerator, and returns a bool MoveNext () instance method with public in the type and the current instance property of public.
In-depth understanding of IEnumerable and IEnumerator