"Go" C # Learning Iterator implementation Enumerator

Source: Internet
Author: User

Http://www.cnblogs.com/zouzf/archive/2012/02/22/2362954.html

I beginner C #, this article is only for personal arrangement of ideas, where said is not right, please give us a lot of advice, extremely grateful!

The previous article implemented the Foreach function for a custom class, but implementing the IEnumerator interface (including the MoveNext, reset, and current properties) in order to get the enumerator for the GetEnumerator function is a bit complicated and cumbersome.

Already know: The main class implements the GetEnumerator function can foreach, and implementation of the IEnumerator interface is just one way to implement GetEnumerator function, there are other ways to implement the GetEnumerator function? Yes, c#2.0 provides us with a very simple way to implement the GetEnumerator function, which is to use an iterator! (Remember, the iterators in C # are different from those in C + +)

Here's a commentary from MSDN:

Iterator overview
Iterators are a piece of code that can return an ordered sequence of values of the same type.

An iterator can be used as the code body for a method, operator, or get accessor.

The iterator code returns each element in turn using the yield return statement. Yield break terminates the iteration. For more information, see yield.

You can implement multiple iterators in a class. Each iterator must have a unique name like any class member, and can be called by client code in a foreach statement, as follows: foreach (int x in Sampleclass.iterator2) {}

The return type of the iterator must be IEnumerable, IEnumerator, ienumerable<t>, or ienumerator<t>.

The yield keyword is used to specify the value returned. When the yield return statement is reached, the current position is saved. The next time the iterator is called, execution will start again from this location.

Part I: Getting an enumerator using the default iterator implementation
1. Define the Person class


Copy Code
1 public class Person
2 {
3 public string Name;
4 public int age;
5
6 Public person (string name, Int. age)
7 {
8 name = name;
9 age = age;
10}
11
public override string ToString ()
13 {
Return "Name:" + name + "\tage:" + age;
15}
16}
Copy Code

2, the definition of PEOPLEENUM1 class, the implementation of the GetEnumerator function (that is, the iterator, which is the default iterator), but the implementation of the process relative to the previous article introduced in the implementation process is much simpler, this is the effect of yield. Yield of the implementation of the principle here is unknown, can be summed up as: GetEnumerator function in the iteration block IEnumerator interface MoveNext, reset method and the current attribute encapsulated, but the essence has not changed, but we use more convenient.

Copy Code
1 public class PeopleEnum1
2 {
3 private person[] _perple;
4
5//constructor
6 Public PeopleEnum1 (person[] list)
7 {
8 _perple = new person[list. Length];
9 for (int i = 0; i < list. Length; i++)
10 {
_perple[i] = List[i];
12}
13}
14
Public IEnumerator GetEnumerator ()
16 {
+ for (int i = 0; i < _perple. Length; i++)
18 {
Yield return _perple[i];
20}
21}
22
23}
Copy Code

3. Main function code


Copy 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
PeopleEnum1 peopleenum = new PeopleEnum1 (persons);
13
+ foreach (var item in Peopleenum)
15 {
System.Console.WriteLine (item);
17
18}
19
System.Console.ReadKey ();
21}
22}
Copy Code
Run, success, hey

Part Two: Custom iterators

The first part implements the class's foreach with the default iterator GetEnumerator, and we can also define our own iterators to get the enumerator we want. In comparison, I would like to enumerate the information of minors in the class, the default iterator is powerless, how to implement the custom iterator?

1. Add an iterator to the PeopleEnum1 class GetChildren, where this iterator is an attribute or can be defined as a function. For elements in a class, only elements of age less than 18 yield return, others do not.


Copy Code
1 public class PeopleEnum1
2 {
3 private person[] _perple;
4
5//constructor
6 Public PeopleEnum1 (person[] list)
7 {
8 _perple = new person[list. Length];
9 for (int i = 0; i < list. Length; i++)
10 {
_perple[i] = List[i];
12}
13}
14
15//Default iterator?
Public IEnumerator GetEnumerator ()
17 {
for (int i = 0; i < _perple. Length; i++)
19 {
Yield return _perple[i];
21}
22}
23
24
25//Custom iterator
Public IEnumerable GetChildren
27 {
Get
29 {
(int i = 0; i < _perple. Length; i++)
31 {
if (_perple[i]. Age < 18)
33 {
Yield return _perple[i];
35}
36}
37}
38}
39}
Copy Code

2. Main function code


Copy Code
1 class Program
2 {
3 static void Main (string[] args)
4 {
5 person[] persons = new person[]
6 {
7 New Person ("AAA", 16),
8 New Person ("BBB", 18),
9 New person ("CCC", 22)
10};
11
12
PeopleEnum1 peopleenum = new PeopleEnum1 (persons);
14
foreach (var item in Peopleenum)
16 {
System.Console.WriteLine (item);
18}
19
20
Console.WriteLine ("Information for minors in the collection");
22
23°c (var item in Peopleenum.getchildren)
24 {
Console.WriteLine (item);
26}
27
System.Console.ReadKey ();
29}
30}
Copy Code

Output Result:

Output Result:

As you can see, the custom iterator GetChildren successfully foreach.

Note: The return type of the default iterator GetEnumerator is IEnumerator, and the class name is directly behind when using foreach. The return type of the custom iterator, GetChildren, is IEnumerable and is followed by the Peopleenum.getchildren (class name, iterator name) when using foreach. It seems as if it is the rule that the principle is not clear.

"Go" C # Learning Iterator implementation 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.