One of the iterator learning: Using the IEnumerable and IEnumerator interfaces

Source: Internet
Author: User

Blogging is a test of my study of one of the achievements and self-summary of a way, will often use this way to carry out technical exchanges and self-summary, in which there will inevitably be mistakes in understanding, but always know not to understand the question, do not understand the truth of schooling!

1, first look at a simple instance

1        int[] MyArray = {1, +, +,343};
2     //It's rarely written like this.
3IEnumerator Myie = Myarray.getenumerator ();//gets the enumerator that needs to be traversed
4Myie. Reset ();// Reset
5 while(Myie. MoveNext ())
6{
7 inti = (int) Myie. Current;//This side involves a boxed operation.
8Console.WriteLine ("Value: {0}", i);
9}
Ten       //Normally, it's written like this.
One       foreach(intIteminchMyArray)
A{
-Console.WriteLine (item. ToString ());
-}

   In most cases, many people use the for and foreach to iterate over the array, but the syntax for the above is rarely used, but the exact origin of the foreach is blurred!

2. Start with foreach

We all know to implement the foreach must implement IEnumerable and IEnumerator interface, only implement them, can realize traversal, so to talk about the origin of foreach, must be the two interfaces to clear point!

Here also want to explain a point is: if the two interfaces have a certain understanding, as long as the implementation of the GetEnumerator method can, and do not need to implement the IEnumerable interface, this is only for the two interfaces have a certain understanding of the friends!

3, IEnumerable

The purpose of this is to make an object that implements this interface an enumerable type.

The IEnumerable interface contains a GetEnumerator method that returns a value of IEnumerator type!

The code is as follows:

1       Public classMycolors:ienumerable
2{
3 string[] colors = {"Red","Yellow","Biue"};
4
5 PublicIEnumerator GetEnumerator ()
6{
7
8 returnColors. GetEnumerator ();
9
Ten}
One}

Then we can do this when the client makes the call!

1     New MyColors ();
2 foreach (string in colors)
3 {
4 Console.WriteLine (item);
5 }

    This can be used to implement the object of this interface foreach traversal, is such a simple case, there may be some people will have doubts, we implemented the IEnumerable interface but did not implement the IEnumerator interface, But don't we say that only the two interfaces are implemented for a foreach traversal? It can be said that when using Forach to traverse, the compiler will go to the object's class to find the GetEnumerator method, find this method and return the object of this IEnumerator (enumerator), and my return is "colors." GetEnumerator () ", is an array object calls itself in the" GetEnumerator "method, so that the array itself implements the IEnumerator interface, then two interfaces are implemented, not a good implementation of the foreach traversal, In fact, when implementing a traversal enumerator, the compiler automatically calls the method in the class that implements the enumerator in the array (which will be discussed in the next article)!

4, IEnumerator

The role of an interface: implementing an enumerable

First look at the definition of the interface:

    

Contains a property of two methods

movenext→ moves the current item to the next item (similar to an index value) and returns a bool value that checks whether the current item is outside the enumerator range!

current→ gets the value of the current item and returns the type of the object (this will involve packing and unpacking problems → When the generics are referred to later)!

reset→, as the name implies, restores some values to their default values, such as returning the current item to the default state value!

The code is as follows:

1      Public classMyienumerator:ienumerator
2{
3
4 string[] colors;//define an array to store the data
5 intPosition =-1;//define the default value of the current item, that is, the index value, the first to know the index of the array starting from "0", how to default set him to "1", and finally to understand that this setting is reasonable!
6
7 PublicMyienumerator (string[] colors)
8{
9 This. Colors =New string[Colors. Length];
Ten
One for(inti =0; I < This. Colors. Length; i++)
A{
- This. colors[i] = colors[i];
-}
the}
-
- Public ObjectCurrent//gets the corresponding value based on the current item
-{
+ Get
-{
+ returnColors[position];//returns the value of the current item, but does a boxed operation!
A}
at}
-
- Public BOOLMoveNext ()//move to the next item
-{
- if(Position < colors. Length-1)//This is the setting of the default value of-1 based on
-{
inposition++;
- return true;
to}
+ Else
-{
the return false;
*}
$}
Panax Notoginseng
- Public voidReset ()//Resets the value of the current item, reverting to the default value
the{
+ This. Position =-1;
A}
the}

In the 3rd IEnumerable interface, the GetEnumerator method is to get the enumerator to traverse, and when we do not create our own class to iterate through the enumerator, we are using the array's method of iterating through the enumerator (the enumerable type of the array and the enumerator are discussed in the next article). But this is sometimes not suitable for us, we need to customize a more suitable for ourselves, so we want to create our own enumerator class (that is, the above code), the 3rd and 4th code together (change a little bit of code), as follows:

1       Public classMyColors//: IEnumerable
2{
3 string[] colors = {"Red","Yellow","Biue"};
4
5 PublicIEnumerator GetEnumerator ()
6{
7 return NewMyienumerator (colors);
8
9 //This is where we're going to change, returning a type that we created, not the IEnumerator object that returned the array, but the enumerator object we created ourselves →myienumerator
Ten}
One}

The client is not to change the code, and then just use the foreach Direct traversal on it!

5. About enumerable types and enumerators

① enumerable type → implement IEnumerable interface, you can not directly implement this interface, but there must be a GetEnumerator method, the return value type must be the IEnumerator type, that is, the 4th of the last piece of code in the interface annotation that way!

② enumerator → Implement IEnumerator interface, implement all methods, first, call GetEnumerator returns an enumerator of type IEnumerator, then the compiler implicitly calls the implementation of the methods and properties in the IEnumerator Class!

Summary: So the implementation of the foreach traversal, must reach the above two conditions to traverse the object, they can be written together can also be separated, preferably separate, separation of duties, a class do one thing is always good!

6, illustrations, quoting the pictures in the book

    

Hope that the friends in the garden can have a lot of advice!

One of the iterator learning: Using the IEnumerable and IEnumerator interfaces

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.