代码无实际意义, 贴上代码备忘:
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
using System.Collections;
5
6
namespace ImpEnumeratable
7

{
8
class Collec : IEnumerable
9
{
10
public List<Itor> Items = new List<Itor>();
11
12
13
IEnumerable 成员#region IEnumerable 成员
14
15
public IEnumerator GetEnumerator()
16
{
17
return new Itor(this);
18
}
19
20
#endregion
21
22
public void Add(Itor it)
23
{
24
Items.Add(it);
25
}
26
}
27
28
class Itor : IEnumerator
29
{
30
public string N;
31
32
int posotion = -1;
33
Collec c;
34
35
public Itor(Collec cc)
36
{
37
c = cc;
38
posotion = -1;
39
}
40
41
public Itor(string s)
42
{
43
N = s;
44
}
45
46
IEnumerator 成员#region IEnumerator 成员
47
48
public object Current
49
{
50
get
51
{
52
return (Itor)c.Items[posotion];
53
}
54
}
55
56
public bool MoveNext()
57
{
58
if (posotion >= c.Items.Count - 1)
59
{
60
return false;
61
}
62
else
63
{
64
posotion++;
65
return true;
66
}
67
}
68
69
public void Reset()
70
{
71
posotion = -1;
72
}
73
74
#endregion
75
}
76
77
78
class Program
79
{
80
static void Main(string[] args)
81
{
82
Collec cols = new Collec();
83
84
Itor it01 = new Itor("Hello ");
85
Itor it02 = new Itor("World");
86
87
cols.Add(it01);
88
cols.Add(it02);
89
90
foreach (Itor i in cols)
91
{
92
Console.WriteLine(i.N);
93
}
94
}
95
}
96
}
97

2

3

4

5

6

7



8

9



10

11

12

13


14

15

16



17

18

19

20

21

22

23



24

25

26

27

28

29



30

31

32

33

34

35

36



37

38

39

40

41

42



43

44

45

46


47

48

49



50

51



52

53

54

55

56

57



58

59



60

61

62

63



64

65

66

67

68

69

70



71

72

73

74

75

76

77

78

79



80

81



82

83

84

85

86

87

88

89

90

91



92

93

94

95

96

97

一般将Itor类放入Collec 内部声明, 集合和集合中的元素紧耦合。 还可保证类型安全。
可以实现范型接口 public interface IEnumerator<T> : IDisposable, IEnumerator
public interface IEnumerable<T> : IEnumerable
来实现范型版本。