C#学习笔记 IEumerable接口 IEumerator接口

来源:互联网 发布:域名不以封疆之界 编辑:程序博客网 时间:2024/06/06 13:19

foreach语句,就是调用GetEnumerator()方法,得到一个数组的枚举器,然后在while循环中判断MoveNext(),如果为true,就可以用Current属性来访问数组中的元素。

根据网上的例子,自己打的代码。IEnumerable接口和IEnumerator接口都在System。Collections里。

using System;using System.Collections;namespace Simple{public class MainEntryPoint{static int Main(string[] args){Person[] pArray = new Person[]{new Person("July","Wu"),new Person("Joyn","Wu"),new Person("John","Wu")};foreach(Person i in pArray){Console.WriteLine(i);}return 0;}}//用户类public class Person{public string firstName;public string lastName;public Person(string firstName, string lastName){this.firstName = firstName;this.lastName = lastName;}public override string ToString(){return firstName+" "+lastName;}}//实现了IEnumerable接口的用户数组的类public class People : IEnumerable{private Person[] people;public People(Person[] pArray){people = new Person[pArray.Length];for(int i = 0; i < pArray.Length; i++){people[i] = new Person(pArray[i].firstName,pArray[i].lastName);}}IEnumerator IEnumerable.GetEnumerator()//显示的实现了接口中的GetEnumerator()方法{return (IEnumerator)GetEnumerator();}public IEnumerator GetEnumerator()//方法的真正实现{return new PeoEnum(people);}}public class PeoEnum : IEnumerator{public Person[] people; int position = -1;//当前指向的元素的前面一个元素public PeoEnum(Person[] people){this.people = people;}public bool MoveNext()//判断是否还有元素{position++;return (position < people.Length);}public void Reset()//重置{position = -1;}object IEnumerator.Current//返回当前元素的对象{get{return Current;}}public Person Current{get{try{return people[position];}catch (IndexOutOfRangeException){throw new InvalidOperationException();}}}}}


0 0
原创粉丝点击