C#IEnumerable 接口
IEnumerable 接口
公开枚举数,该枚举数支持在非泛型集合上进行简单迭代。
命名空间:System.Collections
- public class Person
- {
- public string firstName;
- public string lastName;
- public Person(string fName, string lName)
- {
- this.firstName = fName;
- this.lastName = lName;
- }
- }
- public class People : IEnumerable
- {
- private Person[] _person;
- public People(Person[] pArray)
- {
- _person = new Person[pArray.Length];
- for (int i = 0; i < pArray.Length; i++)
- _person[i] = pArray[i];
- }
- public PeopleEnum GetEnumerator()//返回PeopleEnum当前实例
- {
- return new PeopleEnum(_person);
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return (IEnumerator)GetEnumerator();
- }
- }
- public class PeopleEnum : IEnumerator
- {
- int position = -1;
- public Person[] _person;
- public PeopleEnum(Person[] list)
- {
- _person = list;
- }
- public Person Current
- {
- get
- {
- try { return _person[position]; }
- catch (IndexOutOfRangeException) { throw new InvalidOperationException(); }
- }
- }
- object IEnumerator.Current
- {
- get { return Current; }
- }
- public bool MoveNext()
- {
- position++;
- return (position < _person.Length);
- }
- public void Reset()
- {
- position = -1;
- }
- }
public class Person { public string firstName; public string lastName; public Person(string fName, string lName) { this.firstName = fName; this.lastName = lName; } } public class People : IEnumerable { private Person[] _person; public People(Person[] pArray) { _person = new Person[pArray.Length]; for (int i = 0; i < pArray.Length; i++) _person[i] = pArray[i]; } public PeopleEnum GetEnumerator()//返回PeopleEnum当前实例 { return new PeopleEnum(_person); } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)GetEnumerator(); } } public class PeopleEnum : IEnumerator { int position = -1; public Person[] _person; public PeopleEnum(Person[] list) { _person = list; } public Person Current { get { try { return _person[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } object IEnumerator.Current { get { return Current; } } public bool MoveNext() { position++; return (position < _person.Length); } public void Reset() { position = -1; } }
测试一下:
- static void Main(string[] args)
- {
- Person[] peopleArray = new Person[3]
- {
- new Person("John", "Smith"),
- new Person("Jim", "Johnson"),
- new Person("Sue", "Rabon")
- };
- People peopleList = new People(peopleArray);
- foreach (Person p in peopleList)
- Console.WriteLine((p.firstName + " " + p.lastName));
- Console.ReadKey();
- }
static void Main(string[] args) { Person[] peopleArray = new Person[3] { new Person("John", "Smith"), new Person("Jim", "Johnson"), new Person("Sue", "Rabon") }; People peopleList = new People(peopleArray); foreach (Person p in peopleList) Console.WriteLine((p.firstName + " " + p.lastName)); Console.ReadKey(); }