This article is mainly for you to introduce in detail the principle of foreach in C #, with a certain reference value, interested in small partners can refer to
This article mainly records my experience in learning the principle of foreach traversal in C #.
The traversal of features in a collection is a common practice in all encodings, so most programming languages write this process into syntax, such as foreach in C #. You will often see the following traversal code:
var lststr = new List<string> {"A", "B"}; foreach (Var str in lststr) { Console.WriteLine (str); }
The actual execution of this code is:
var lststr = new List<string> {"A", "B"}; ienumerator<string> enumeratorlst = Lststr.getenumerator (); while (Enumeratorlst.movenext ()) { Console.WriteLine (enumeratorlst.current); }
The GetEnumerator () method and the Ienumerator<string> type are found, which involves the concept of enumerable types and enumerators.
For ease of understanding, the following is a non-generic example:
Summary:// exposes the enumerator, which supports simple iterations on non-generic collections. Public Interface IEnumerable { //Summary: // Returns an enumerator that iterates through the collection. ///// Returns the result: // The System.Collections.IEnumerator object that can be used to iterate through the collection. IEnumerator GetEnumerator (); }
A class that implements this interface is called an enumerable type and is a flag that can be traversed with foreach.
The return value of Method GetEnumerator () is an enumerator that can be understood as a cursor.
Summary:// supports simple iterations for non-generic collections. Public Interface IEnumerator { //Summary: // Gets the current element in the collection. //// Returns the result: // The current element in the collection. ///// exception: / /System.InvalidOperationException://The Enumerator is positioned before the first element of the collection or after the last element. object current {get;} Summary: // Advances the enumerator to the next element of the collection. ///// Returns the result: // True if the enumerator is successfully pushed to the next element, or False if the enumerator crosses the end of the collection. ///// Exception: // System.InvalidOperationException: // The collection was modified after the enumerator was created. bool MoveNext (); //Summary: // Sets the enumerator to its initial position, which precedes the first element in the collection. ///// Exception: // System.InvalidOperationException: // The collection was modified after the enumerator was created. void Reset (); }
The following is an example of customizing an iterator (https://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx):
Using system;using system.collections;//simple business Object.public class person{public person (string fName, String l Name) {this.firstname = FName; This.lastname = LName; } public string FirstName; public string LastName;} Collection of person objects. This class//implements IEnumerable so the it can be used//with ForEach Syntax.public class people:ienumerable{Priva Te person[] _people; Public people (person[] parray) {_people = new person[parray.length]; for (int i = 0; i < parray.length; i++) {_people[i] = Parray[i]; }}//implementation for the GetEnumerator method. IEnumerator Ienumerable.getenumerator () {return (IEnumerator) GetEnumerator (); } public Peopleenum GetEnumerator () {return new peopleenum (_people); }}//when you implement IEnumerable, you must also implement Ienumerator.public class peopleenum:ienumerator{public Pe Rson[] _people; Enumerators is positioned before the first element//until the firstMoveNext () call. int position =-1; Public Peopleenum (person[] list) {_people = list; } public bool MoveNext () {position++; Return (Position < _people. Length); } public void Reset () {position =-1; } object IEnumerator.Current {get {return current; }} public person current {get {try {return _people[position]; } catch (IndexOutOfRangeException) {throw new InvalidOperationException (); }}}}class app{static void Main () {person[] Peoplearray = new Person[3] {new Person ("John", "Smith"), New Person ("Jim", "Johnson"), New Person ("Sue", "Rabon"),}; People peoplelist = new people (Peoplearray); foreach (person p in Peoplelist) Console.WriteLine (P.firstname + "" + p.lastname); }}/* This code produces output similar to the following: * * John Smith * Jim Johnson * Sue rabon * * *
After we have the keyword yield, we can create an enumerator in this way:
Using system;using system.collections;//simple business Object.public class person{public person (string fName, String l Name) {this.firstname = FName; This.lastname = LName; } public string FirstName; public string LastName;} Collection of person objects. This class//implements IEnumerable so the it can be used//with ForEach Syntax.public class people:ienumerable{Priva Te person[] _people; Public people (person[] parray) {_people = new person[parray.length]; for (int i = 0; i < parray.length; i++) {_people[i] = Parray[i]; }}//implementation for the GetEnumerator method. IEnumerator Ienumerable.getenumerator () {for (int i = 0; i < _people. Length; i++) {yield return _people[i]; }}}class app{static void Main () {person[] Peoplearray = new Person[3] {new Person ("John", "Smith"), New Person ("Jim", "Johnson"), New Person ("Sue", "Rabon"),}; People peoplelist = new people (Peoplearray); FoReach (person p in Peoplelist) Console.WriteLine (P.firstname + "" + p.lastname); }}