"C #" 26. About IEnumerable and IEnumerator

Source: Internet
Author: User

Finally, the master's all the coursework has been completed ...

write a little about the concepts of IEnumerator and IEnumerable, which were used before to write financial models, and not too clear, these two days to see C#in Depth, think inside explanation is good, although the example is a bit wrong. So write an article about these two concepts today.

First of all, I have a preconceived notion that IEnumerable is like an array type. The thought of arrays makes it easy to associate the syntax of a foreach traversal. So the question is, how is foreach implemented? The answer is that when you call foreach, the data type of this array-like IEnumerable will call a method inside of it-GetEnumerator

, he returns a IEnumerator type.

Specifically, this IEnumerator type contains the Current,movenext and reset methods. foreach calls these three methods each time it executes.

Here's an example: In this case, myarray is a type that implements the Ienumerable<int>, and one of the most important methods is GetEnumerator; Returns an implementation ienumerator<int > Iterator, itself this (MyArray) as the parameter. In the main function, the for each object is the MyArray type data, and each loop calls MoveNext first and then current. Reset I think it's supposed to be called for the entire end, including such things as Dispose and so on, but I'm not textual. Finally, we see the result.

Finally, it is worth mentioning that GetEnumerator can use yield return, so it does not need to iterator this type, very intuitive and convenient, is C # 2.0 and later version of the syntax.

    public class Myarray:ienumerable<int> {public int[] values;        Public MyArray (int[] array) {this.values = array; }//Implement Interface IEnumerable public Ienumerator<int> GetEnumerator () {return new Iterator (th            IS); for (int i = 0; i < values. Length;            i++)//{//yield return values[i]; }} System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () {thro        W new NotImplementedException (); }}//ienumerator implementation class, MyArray as member public class Iterator:ienumerator<int> {private MyArray Mmyarray        ;        private int mposition;            Public Iterator (MyArray MyArray) {this.mmyarray = MyArray;        This.mposition =-1; }//implement IEnumerator interface public int-current {get {///If MoveNext is not executed           Line current will error     Or execute to the last element after if (mposition = = -1| |                Mposition = = mMyArray.values.Length) {throw new Exception ();            } else return mmyarray.values[mposition];            }} public bool MoveNext () {bool isnotend;                if (Mposition < mmyarray.values.length-1) {mposition++;            Isnotend = true;            } else Isnotend = false;        return isnotend;        } public void Reset () {mposition =-1; } public void Dispose () {} object System.Collections.IEnumerator.Current {get {th Row new NotImplementedException (); }}} class program {static void Main (string[] args) {MyArray array = new Myarr            Ay (new int[] {1, 2, 3, 4, 5}); foreach (var item in array) {Console.WriteLine (item. TOstring ());        } console.read (); }    }



"C #" 26. About IEnumerable and IEnumerator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.