Welcome

首页 / 软件开发 / C# / C#中IEnumrator的枚举数和IEnumerable接口

C#中IEnumrator的枚举数和IEnumerable接口2014-10-01声明IEnumerator的枚举数

要创建非泛型接口的枚举数,必须声明实现IEnumerator接口的类,IEnumerator接口有如下特性:

1、她是System.Collections命名空间的成员

2、它包含3个方法Current、MoveNext和Reset

例如:下面代码实现了一个列出颜色名数组的枚举数类:

using System.Collections; class ColorEnumerator:IEnumerator{string [] Colors;int Position=-1; public object Current{get{if(Position==-1)return new Exception();if(Position==Colors.Length)return new Exception();return Colors[Position];}} public bool MoveNext(){if(Position<Colors.Length-1){Position++;return true;}else{return false;}} pulic void Reset(){Position=-1;} public ColorEnumerator(string[] theColors){Colors=new string[theColors.Length];for(int i=0;i<theColors.Length;i++){Colors[i]=theColors[i];}}}

IEnumerable接口只有一个成员——GetEnumerator方法,它返回对象的枚举数。

如下代码给出一个使用上面ColorEnumerator枚举数类的实例,要记住,ColorEnumerator实现了IEnumerator。

class MyColors:IEnumerable{string[] Colors={"","",""};public IEnumerator GetEnumerator()//返回Ienumerator类型的对象,也就是可枚举类型{return new ColorEnumerator(Colors);}}