C # Learning Note: The foreach principle

Source: Internet
Author: User

This essay is the last essay on the C # keyword: yield extension.

About foreach

First of all, for foreach , everyone should be very familiar with, here is a simple description.

The foreach statement is used to implement System.Collections.IEnumerable or system.collections.generic.ienumerable<t each element in the > interface's array or object collection is iterate, but cannot be used to add or remove items from the source collection, which may cause unpredictable side effects. If you need to add or remove items from the source collection, you should use a for loop.

the principle of foreach

A foreach statement is designed to be used with an enumerable type, as long as its traversal object is an enumerable type (implemented IEnumerable), such as an array. The calling process is as follows:

    1. Call the GetEnumerator () method and return a IEnumerator reference.
    2. Invokes the MoveNext () method of the returned IEnumerator interface.
    3. If the MoveNext () method returns True, a reference to the object is obtained using the current property of the IEnumerator interface for the foreach loops.
    4. Repeat the previous two steps until the MoveNext () method returns false , and the loop stops at this point.

We can simulate the execution of foreach through code, as follows:

Static voidMain () {int[] arr = {1,2,3,4,5};//declares and initializes an array. IEnumerator ie = arr. GetEnumerator ();//invokes the GetEnumerator method of an enumerable type to obtain an enumerator object.      while(ie. MoveNext ())//call the MoveNext method of the IEnumerator interface to move to the next item. Implements the traversal array.     {        inti = (int) ie. Current;//call the current method of the IEnumerator interface to get the present item. Note that it returns an object type and requires a cast type. Console.Write ("{0}", i); }    //output:1 2 3 4 5Console.readkey ();}

Of course, if you use foreach , it's very simple, as follows:

 static  void   Main () { int  [] arr = {1 , 2 , 3 ,     4 , };  foreach  (int  item in   arr. {Console.Write (  " {0}    //  Output:1 2 3 4 5   Console.readkey ();}  

Next, look at an example of a complex point, as follows:

classprogram{Static voidMain () {//Create a Tokens instance.Tokens f =NewTokens ("This is a sample sentence.",New Char[] {' ','-' }); //Display the tokens.        foreach(stringIteminchf) {System.Console.WriteLine (item); }        //Output:// This// is//a//Sample//sentence.Console.readkey (); }} Public classtokens:ienumerable{Private string[] elements;  PublicTokens (stringSourceChar[] delimiters) {        //The constructor parses the string argument into tokens.elements =source.    Split (delimiters); }    //The IEnumerable interface requires implementation of method GetEnumerator.     PublicIEnumerator GetEnumerator () {return NewTokenenumerator ( This); }    //Declare an inner class that implements the IEnumerator interface.    Private classTokenenumerator:ienumerator {Private intPosition =-1; PrivateTokens t;  Publictokenenumerator (Tokens t) { This. T =T; }        //The IEnumerator interface requires a MoveNext method.         Public BOOLMoveNext () {if(Position < t.elements.length-1) {Position++; return true; }            Else            {                return false; }        }        //The IEnumerator interface requires a Reset method.         Public voidReset () {position= -1; }        //The IEnumerator interface requires a current method.         Public ObjectCurrent {Get            {                returnT.elements[position]; }        }    }}
Reference documents
    1. The original of foreach in C #
    2. Http://www.cnblogs.com/mcgrady/archive/2011/11/12/2246867.html
    3. Https://msdn.microsoft.com/zh-cn/library/9yb8xew9%28v=vs.110%29.aspx

C # Learning Note: The foreach principle

Related Article

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.