由集合所定义的只能有一个这样的无参数 GetEnumerator方法,但经常有多种枚举方式,以及通过参数控制枚举的方法。在这种情况下,集合可以使用迭代器实现返回可枚举接口之一的属性和方法。如下:
1 class MusicTitles
2 {
3 string[] names = {
4 "Tubular Bells",
5 "Hergest Ridge",
6 "Ommadawn",
7 "Platinum"
8 };
9
10 public IEnumerator GetEnumerator()
11 {
12 for (int i = 0; i < 4; i++)
13 {
14 yield return names[i];
15 }
16 }
17
18 public IEnumerable Reverse()
19 {
20 for (int i = 3; i >= 0; i--)
21 {
22 yield return names[i];
23 }
24 }
25
26 public IEnumerable Subset( int index, int length)
27 {
28 for (int i = index; i < index + length; i++)
29 {
30 yield return names[i];
31 }
32 }
33
34 public static void testMusicTitels()
35 {
36 MusicTitles titles = new MusicTitles();
37 foreach (string title in titles)
38 {
39 Console.WriteLine(title);
40 }
41
42 Console.WriteLine();
43 Console.WriteLine("reverse");
44 foreach (string title in titles.Reverse())
45 {
46 Console.WriteLine(title);
47 }
48 Console.WriteLine();
49 Console.WriteLine("subset");
50 foreach (string title in titles.Subset(2, 2))
51 {
52 Console.WriteLine(title);
53 }
54 }
55 }
这个例子改自:c#3.0 高级编程
2 {
3 string[] names = {
4 "Tubular Bells",
5 "Hergest Ridge",
6 "Ommadawn",
7 "Platinum"
8 };
9
10 public IEnumerator GetEnumerator()
11 {
12 for (int i = 0; i < 4; i++)
13 {
14 yield return names[i];
15 }
16 }
17
18 public IEnumerable Reverse()
19 {
20 for (int i = 3; i >= 0; i--)
21 {
22 yield return names[i];
23 }
24 }
25
26 public IEnumerable Subset( int index, int length)
27 {
28 for (int i = index; i < index + length; i++)
29 {
30 yield return names[i];
31 }
32 }
33
34 public static void testMusicTitels()
35 {
36 MusicTitles titles = new MusicTitles();
37 foreach (string title in titles)
38 {
39 Console.WriteLine(title);
40 }
41
42 Console.WriteLine();
43 Console.WriteLine("reverse");
44 foreach (string title in titles.Reverse())
45 {
46 Console.WriteLine(title);
47 }
48 Console.WriteLine();
49 Console.WriteLine("subset");
50 foreach (string title in titles.Subset(2, 2))
51 {
52 Console.WriteLine(title);
53 }
54 }
55 }