IEnumerable 接口
公开枚举数,该枚举数支持在非泛型集合上进行简单迭代。
IEnumberable接口只有一个方法:
GetEnumerator 返回一个循环访问集合的枚举数。
GetEnumerator C#语法:
IEnumerator GetEnumerator()
示例:
下面的代码示例演示如何实现自定义集合的 IEnumerable 和 IEnumerator 接口。在此示例中,没有显式调用这些接口的成员,但实现了它们,以便支持使用 foreach(在 Visual Basic 中为 For Each)循环访问该集合。
[c-sharp] view plaincopy
01.using System;
02.using System.Collections;
03.
04.public class Person
05.{
06. public Person(string fName, string lName)
07. {
08. this.firstName = fName;
09. this.lastName = lName;
10. }
11.
12. public string firstName;
13. public string lastName;
14.}
15.
16.public 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.
35.public 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.class App
76.{
77. static void Main()
78. {
79. Person[] peopleArray = new Person[3]
80. {
81. new Person("John", "Smith"),
82. new Person("Jim", "Johnson"),
83. new Person("Sue", "Rabon"),
84. };
85.
86. People peopleList = new People(peopleArray);
87. foreach (Person p in peopleList)
88. Console.WriteLine(p.firstName + " " + p.lastName);
89.
90. }
91.}
92.
93./* This code produces output similar to the following:
94. *
95. * John Smith
96. * Jim Johnson
97. * Sue Rabon
98. *
99. */
|