IEnumerable 接口

ContractedBlock.gif ExpandedBlockStart.gif View Code
  1 using System;
2 using System.Collections;
3
4 public 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
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 IEnumerator IEnumerable.GetEnumerator()
30 {
31 return (IEnumerator) GetEnumerator();
32 }
33
34 public PeopleEnum GetEnumerator()
35 {
36 return new PeopleEnum(_people);
37 }
38 }
39
40 public class PeopleEnum : IEnumerator
41 {
42 public Person[] _people;
43
44 // Enumerators are positioned before the first element
45 // until the first MoveNext() call.
46 int position = -1;
47
48 public PeopleEnum(Person[] list)
49 {
50 _people = list;
51 }
52
53 public bool MoveNext()
54 {
55 position++;
56 return (position < _people.Length);
57 }
58
59 public void Reset()
60 {
61 position = -1;
62 }
63
64 object IEnumerator.Current
65 {
66 get
67 {
68 return Current;
69 }
70 }
71
72 public Person Current
73 {
74 get
75 {
76 try
77 {
78 return _people[position];
79 }
80 catch (IndexOutOfRangeException)
81 {
82 throw new InvalidOperationException();
83 }
84 }
85 }
86 }
87
88 class App
89 {
90 static void Main()
91 {
92 Person[] peopleArray = new Person[3]
93 {
94 new Person("John", "Smith"),
95 new Person("Jim", "Johnson"),
96 new Person("Sue", "Rabon"),
97 };
98
99 People peopleList = new People(peopleArray);
100 foreach (Person p in peopleList)
101 Console.WriteLine(p.firstName + " " + p.lastName);
102
103 }
104 }
105
106 /* This code produces output similar to the following:
107 *
108 * John Smith
109 * Jim Johnson
110 * Sue Rabon
111 *
112 */

转载于:https://www.cnblogs.com/XiaoJie85/articles/2217158.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值