我们知道在.net中有两个接口用来实现枚举数的,它就是System.Collections 命名空间 下的 IEnumerable和IEnumerator接口。简单地说IEnumerator接口是用来实现枚举器,而IEnumerable接口是用来公开枚枚举器的。
下面来看看MSDN上是怎么说的。
IEnumerator 接口
支持对非泛型集合的简单迭代。也就是枚举
方法
MoveNext 将枚举数推进到集合的下一个元素。
Reset 将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。
属性
Current 获取集合中的当前元素。
这个接口是用来实现枚举器的,如下代码
Code
1public class PeopleEnum : IEnumerator
2{
3 public Person[] _people;
4
5 // Enumerators are positioned before the first element
6 // until the first MoveNext() call.
7 int position = -1;
8
9 public PeopleEnum(Person[] list)
10 {
11 _people = list;
12 }
13
14 public bool MoveNext()
15 {
16 position++;
17 return (position < _people.Length);
18 }
19
20 public void Reset()
21 {
22 position = -1;
23 }
24
25 public object Current
26 {
27 get
28 {
29 try
30 {
31 return _people[position];
32 }
33 catch (IndexOutOfRangeException)
34 {
35 throw new InvalidOperationException();
36 }
37 }
38 }
39}
40
上面是对IEnumerator接口的实现,现在有了一个PeopleEnum的枚举器,它用来枚举People对象。
那IEnumerable接口有什么用了,它就是用来公开枚举器的。如下代码:
方法
GetEnumerator 返回一个循环访问集合的枚举数。
Code
1using System;
2using System.Collections;
3
4public class Person
5{
6 public Person(string fName, string lName)
7 {
8 this.firstName = fName;
9 this.lastName = lName;
10 }
11
12 public string firstName;
13 public string lastName;
14}
15
16public class People : IEnumerable
17{
18 private Person[] _people;
19 public People(Person[] pArray)
20 {
21 _people = new Person[pArray.Length];
22
23 for (int i = 0; i < pArray.Length; i++)
24 {
25 _people[i] = pArray[i];
26 }
27 }
28
29 public IEnumerator GetEnumerator()
30 {
31 return new PeopleEnum(_people);
32 }
33}
34
35public class PeopleEnum : IEnumerator
36{
37 public Person[] _people;
38
39 // Enumerators are positioned before the first element
40 // until the first MoveNext() call.
41 int position = -1;
42
43 public PeopleEnum(Person[] list)
44 {
45 _people = list;
46 }
47
48 public bool MoveNext()
49 {
50 position++;
51 return (position < _people.Length);
52 }
53
54 public void Reset()
55 {
56 position = -1;
57 }
58
59 public object Current
60 {
61 get
62 {
63 try
64 {
65 return _people[position];
66 }
67 catch (IndexOutOfRangeException)
68 {
69 throw new InvalidOperationException();
70 }
71 }
72 }
73}
74
75
这样就可以用foreach语句访问people类中的person对象。这也是一个叠代器设计模式
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/12639172/viewspace-620407/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/12639172/viewspace-620407/