C # implement foreach in a custom class of learning

Source: Internet
Author: User
Document directory
  • Part 2: Nature of foreach implementation

I am a beginner in C #. This article is only intended for my personal purposes. I am very grateful for your suggestions!

Purpose: To implement the ienumerable interface so that a custom class can use a foreach statement to traverse its own elements

Prerequisites: the array can be traversed by the foreach statement because the base classes of all arrays are system. array, while system. the array class implements the ienumerable interface. You can use the getenumerator method to provide an object called enumerator as needed. The number of enumerations can return the elements of the requested array in turn. (Note: The number of enumerators in C # is similar to the iterator in C ++, And the iterator in C # is another meaning. I don't know if this is my understanding, do you ?)

 

Part 1: implement the foreach Statement by inheriting the ienumerable interface Step 1: Create the person class

 

View code

 1     public class Person
2 {
3 string Name;
4 int Age;
5
6 public Person(string name, int age)
7 {
8 Name = name;
9 Age = age;
10 }
11
12 public override string ToString()
13 {
14 return "Name: " + Name + "\tAge: " + Age;
15 }
16 }


Step 2: Create the peopleenum class, which inherits the ienumerator interface and implements the movenext, reset method, and current attribute view code in the ienumerator interface.

 1     public class PeopleEnum : IEnumerator
2 {
3 private Person[] _people;
4 int position = -1;
5
6 public PeopleEnum(Person[] list)
7 {
8 _people = list;
9 }
10
11 public bool MoveNext()
12 {
13 position++;
14 return (position < _people.Length);
15 }
16
17 public void Reset()
18 {
19 position = -1;
20 }
21
22 public object Current
23 {
24 get
25 {
26 return _people[position];
27 }
28 }
29
30 }

 

Step 3: Create a people class that inherits the ienumerable interface and implements the getenumerator method. The getenumerator method is used to obtain the number of enumerations (the returned value is ienumerator type, that is, the number of enumerations ), here, the number of enumerations is obtained by returning an instance of the peopleenum class. View code

 1     public class People : IEnumerable
2 {
3 private Person[] _people;
4 public People(Person[] pArray)
5 {
6 _people = new Person[pArray.Length];
7 for (int i = 0; i < pArray.Length; i++)
8 {
9 _people[i] = pArray[i];
10
11 }
12 }
13
14 public IEnumerator GetEnumerator()
15 {
16 return new PeopleEnum(_people);
17 }
18 }

 

Step 4: The people class implements the ienumerable interface, so the people class instance can use foreach to traverse its own elements. The main function test code is as follows:

 

 1     class Program
2 {
3 static void Main(string[] args)
4 {
5 Person[] persons = new Person[]
6 {
7 new Person("aaa", 20),
8 new Person("bbb", 21),
9 new Person("ccc", 22)
10 };
11
12 People peopleList = new People(persons);
13
14 foreach (var item in peopleList)
15 {
16 System.Console.WriteLine(item);
17 }
18
19 System.Console.ReadKey();
20 }
21 }

 

 

Output:

 

Part 2: Nature of foreach implementation

In the second step of the first part, create the peopleenum class and implement the movenext, reset method, and current attributes in the inherited ienumerator interface. In fact, this class already has the conditions for traversing its own elements.

Change the test code in the main function to the following: Run-> output. The result is the same.

View code

 1     class Program
2 {
3 static void Main(string[] args)
4 {
5 Person[] persons = new Person[]
6 {
7 new Person("aaa", 20),
8 new Person("bbb", 21),
9 new Person("ccc", 22)
10 };
11
12 while (peopleEnum.MoveNext())
13 {
14 System.Console.WriteLine(peopleEnum.Current);
15 }
16
17 System.Console.ReadKey();
18 }
19 }

 

But you cannot use the foreach statement. Why? Because the foreach statement class must provide the getenumerator method to obtain the number of enumerations of the class, then, the compiler calls the movenext, reset, and current attributes in the ienumerator interface to traverse class elements.

Add a getenumerator method to the peopleenum class.

1         public IEnumerator GetEnumerator()
2 {
3 return this;
4 }

 

The main function test code is changed to the following:

 1     class Program
2 {
3 static void Main(string[] args)
4 {
5 Person[] persons = new Person[]
6 {
7 new Person("aaa", 20),
8 new Person("bbb", 21),
9 new Person("ccc", 22)
10 };
11
12
13 PeopleEnum peopleEnum = new PeopleEnum(persons);
14
15 foreach (var item in peopleEnum)
16 {
17 System.Console.WriteLine(item);
18
19 }
20
21 System.Console.ReadKey();
22 }
23 }

Run, succeeded!

Conclusion: To implement foreach for a class, you must provide the getenumerator method to obtain the enumerated number of the class (that is, to return a variable of the ienumerator interface type ). There are many ways to implement the getenumerator method (or get the number of enumerations). This article uses the method to implement the ienumerable interface (essentially implementing the ienumerator interface, only the getenumerator method is removed ). Other methods, such as using the iterator to implement the getenumerator method, are provided in the next article. Thank you!

 

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.