C # Enumerator

Source: Internet
Author: User

1: Enumerators and enumerable types

We know that using foreach, you can iterate through the elements in the array. So why the array can be handled by a foreach statement, let's discuss the problem below.

2: Using the foreach statement

We know that when we use the foreach statement, the statement takes each element of the array in turn.

For example, the following code:

1             int[] arr = {1,2,3,4,5,6 };2             foreach(intArryincharr)3             {4Console.WriteLine ("Array value::{0}", Arry);5}

The output effect is

Why arrays can be traversed with foreach because arrays can provide an object called an enumerator (enumerator) On demand, the enumerator can return the elements in the requested array in turn, the enumerator knows the order of the items, and tracks its position in the sequence. Returns the current item of the request, in turn.

For a type that has an enumerator, there must be a way to get it this type. The way to get an object enumerator is to call the Getenumrator method of the object, and the type that implements the Getenumrator method is called an enumerable type. Then the array is an enumerable type.

Demonstrates the relationship between an enumerable type and an enumerator.

The foreach structure is designed to be used with an enumerable type, as long as the traversal object to it is an enumerable type, such as an array.

1: Gets an enumerator for the object by calling the Getenumrator method.

2: Request each item from the enumerator and use it as an iterator, the code can read the variable, but it cannot be changed

foreach (Type VarName in Enumrableobject)

{

...

}

Enumrableobjec must be an enumerable type.

2:ienumrator interface

The Ienumrator interface contains 3 function members: Current, MoveNext, and reset;

. Current is the property of the item in the returned sequence. (Note: Current is a read-only property that returns a reference to type object, so you can return any type)

. MoveNext is the way to advance the enumerator position to the next item in the collection. It also has a Boolean value that indicates whether the new location is a valid location.

Note: If the returned position is valid, the method returns true;

If the new location is invalid, the method returns false;

The original position of the enumerator precedes the first item in the sequence, so MoveNext must be called before the first use of current.

. Reset is the method that resets the position to its original state.

Now let's figure out the relationship between them.

With the enumerator for the collection, we can use the MoveNext and current members to imitate the Foreach loop to iterate through the items in the collection, for example, we already know that the array is an enumerable type, so the following code makes the foreach statement manually

Do things automatically.

The code is as follows:

1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Threading.Tasks;6 usingSystem.Collections;7 8 namespaceConsoleApplication19 {Ten     class Program One     { A         Static voidMain (string[] args) -         { -             int[] arr = {1,2,3,4,5,6 }; theIEnumerator ie =arr. GetEnumerator (); -              while(ie. MoveNext ()) -             { -                 inti = (int) ie. Current; +Console.WriteLine ("{0}", i); -             } +         } A     } at}

The result of the program running is

Let's explain the array structure in the code in the diagram.

IEnumerable interface

An array is an enumerable type because the class that implements the IEnumerable interface is implemented because the class that implements the IEnumerable interface is the enumerable class.

The IEnumerable interface has only one member of the--getenumerator () method, which returns an enumerator over the object.

Let's give an example of using IEnumerator and IEnumerable

The following code shows a complete example of an enumerable class called component (spherical). Its enumerator class is shape (shape).

The code is as follows:

1 usingSystem;2 usingSystem.Collections;3 4 namespaceConsoleApplication15 {6     classShape:ienumerator7     {8         string[] _shapes;9         int_position =-1;Ten  One          PublicShape (string[] _theshapes) A         { -_shapes =New string[_theshapes.length]; -              for(inti =0; i < _theshapes.length; i++ ) the             { -_shapes[i] =_theshapes[i]; -             } -         } +  -          PublicObject Current +         { A             Get at             { -                 if(_position = =-1 ) -                     Throw NewInvalidOperationException (); -                 if(_position >=_shapes.length) -                     Throw NewInvalidOperationException (); -                 return_shapes[_position]; in             } -         } to  +          Public BOOLMoveNext () -         { the             if(_position < _shapes.length-1) *             { $_position++;Panax Notoginseng                 return true; -             } the             Else +                 return false; A         } the  +          Public voidReset () -         { $_position =-1; $         } -     } -  the     classcomponent:ienumerable -     {Wuyi         string[] shapes = {"Circular","Spherical","Quadrilateral","Label" }; the          PublicIEnumerator GetEnumerator () -         { Wu             return NewShape (shapes); -         } About     } $  -     class Program -     { -         Static voidMain (string[] args) A         { +Component Comp =NewComponent (); the             foreach(stringOshapeinchcomp) - Console.WriteLine (oshape); $         } the         the     } the}

Operation Result:

If you read this blog, feel that you have something to gain, please click on the bottom right corner of the [recommended]

If you want to reprint this blog, Please specify the source

If you have comments or suggestions for this article, please leave a message

Thank you for reading, please follow me on the following blog

C # Enumerator

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.