One of iterator learning: Use the ienumerable and ienumerator Interfaces

Source: Internet
Author: User

Writing a blog is one of my learning achievements and one of my self-summarization methods. In the future, I will often use this method for technical exchanges and self-summarization. If I do not know this, I will inevitably see errors, however, if you have never understood it, you can ask questions and learn the truth!

1. First, let's look at a simple column.

1 int [] myarray = {1, 32, 43,343 };
2 // rarely written in this way
3 ienumerator myie = myarray. getenumerator (); // gets the number of enumerations to be traversed.
4 myie. Reset (); // Reset
5 while (myie. movenext ())
6 {
7 int I = (INT) myie. Current; // a boxing operation is involved here.
8 console. writeline ("value: {0}", I );
9}
10 // This is generally the case
11 foreach (INT item in myarray)
12 {
13 console. writeline (item. tostring ());
14}

   In most cases, many people use for and foreach to traverse arrays, but the above syntax is rarely used, but the specific origins of foreach are still vague!

 

2. Start with foreach.

We all know that to implement foreach, you must implement the interfaces of ienumerable and ienumerator. Only when you implement them can you traverse them, you must clarify the two interfaces!

One thing to note here is: if you have some knowledge about these two interfaces, you only need to implement the getenumerator method, instead of the ienumerable interface, this is just for friends who have some knowledge about these two interfaces!


3. ienumerable

The specific function is to make the object implementing this interface an enumerated type.

The ienumerable Interface contains a getenumerator method. The returned value is of the ienumerator type!

The Code is as follows:

 1    public class MyColors : IEnumerable
2 {
3 string[] colors = { "Red", "Yellow", "Biue" };
4
5 public IEnumerator GetEnumerator()
6 {
7
8 return colors.GetEnumerator();
9
10 }
11 }

So we can do this when calling the client!

 

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

    In this way, the object implementing this interface can be used for foreach traversal. This is a simple column, and some people may have questions, we implemented the ienumerable interface but did not implement the ienumerator interface. But we didn't mean that only the two interfaces can be used for foreach traversal? It can be said that when we use forach for traversal, the compiler will go to the class of this object to find the getenumerator method, find this method, and return this ienumerator object (enumeration number ), here I return "colors. getenumerator () "is an array object that calls its" getenumerator "method. Therefore, the array itself implements the ienumerator interface, and both interfaces are implemented, in fact, the compiler will automatically call the method in the array to implement the enumerated number class when traversing the enumerated number (This will be discussed in the next article )!

 

4. ienumerator

Function of the interface: implement the enumerative number

First, let's take a look at the interface definition:

    

Contains one attribute and two methods.

Movenext → Move the current item to the next item (similar to the index value) and return a bool value. This bool value is used to check whether the current item has exceeded the enumerated value range!

Current → get the value of the current item and return the type of an object (this will involve the problem of packing and unpacking → it will be involved later when talking about generics )!

Reset → as the name suggests, it restores some values to the default value, for example, restoring the current item to the default value!

The Code is as follows:

1 public class myienumerator: ienumerator
2 {
3
4 string [] colors; // defines an array to store data.
5 Int position =-1; // defines the default value of the current item, that is, the index value. The index of the array starts from "0, how can I set it to "-1" by default? I finally want to understand it. This setting is reasonable!
6
7 public myienumerator (string [] colors)
8 {
9 This. colors = new string [colors. Length];
10
11 For (INT I = 0; I <this. colors. length; I ++)
12 {
13 This. colors [I] = colors [I];
14}
15}
16
17 public object current // obtain the corresponding value based on the current item
18 {
19 get
20 {
21 return colors [position]; // return the value of the current item, but a boxing operation will be performed!
22}
23}
24
25 public bool movenext () // move to the next item
26 {
27 if (position <colors. Length-1) // This is the basis for setting the default value to-1.
28 {
29 position ++;
30 return true;
31}
32 else
33 {
34 return false;
35}
36}
37
38 public void reset () // reset the value of the current item and restore it to the default value
39 {
40 this. Position =-1;
41}
42}

In the ienumerable interface mentioned in the third section, the getenumerator method is used to obtain the number of enumerations to be traversed. When we do not create a class for the number of enumerations, we use the method of traversing the enumerated Number of Array (the enumerated types and enumerated numbers of arrays will be discussed in the next article), but sometimes this is not necessarily suitable for us, we need to customize a more appropriate one for ourselves, so we need to create our own enumerated number class (that is, the code above ), combine the code of the third and fourth points (change the code) as follows:

 

1 public class mycolors //: ienumerable
2 {
3 string [] colors = {"red", "yellow", "bIue "};
4
5 Public ienumerator getenumerator ()
6 {
7 return New myienumerator (colors );
8
9 // here is what we want to change. A self-created type is returned, not the ienumerator object of the array, but the self-created enumeration number object → myienumerator
10}
11}

The client does not need to change the code, and you only need to use foreach to directly traverse it!

5. enumeration types and enumeration numbers

① Enumeration type → implement the ienumerable interface. You do not need to implement this interface directly, but you must have a getenumerator method. The return value type must be ienumerator, that is, the method for writing interface comments in the last code section at the fourth point!

② Enumeration count → implement the ienumerator interface to implement all the methods. First, call getenumerator to return an enumeration number of ienumerator type, and then the compiler will implicitly call the methods and attributes in the ienumerator class!

Conclusion: To achieve foreach traversal, the objects can be traversed only when the preceding two conditions are met. They can be written together or separated. It is best to separate roles and responsibilities, it is always a good thing to do one thing!

 

6. The image in the book is referenced as an illustration.

    

 

I hope my friends in the garden can give me more advice!

Next article: iterator 2: defines the enumerated types and enumerated numbers of arrays and the working principle of the compiler foreach!

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.