【C#】IEnumrator的枚举数和IEnumerable接口

声明IEnumerator的枚举数

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

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

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

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

 1 using System.Collections;
 2 
 3 class ColorEnumerator:IEnumerator
 4 {
 5     string [] Colors;    
 6     int Position=-1;
 7 
 8     public object Current
 9     {
10         get
11         {
12             if(Position==-1)
13                 return new Exception();
14             if(Position==Colors.Length)
15                 return new Exception();
16             return Colors[Position];
17         }
18     }
19 
20     public bool MoveNext()
21     {
22         if(Position<Colors.Length-1)
23         {
24             Position++;
25             return true;
26         }
27         else
28         {
29             return false;
30         }
31     }
32 
33     pulic void Reset()
34     {
35         Position=-1;
36     }
37 
38     public ColorEnumerator(string[] theColors)
39     {
40         Colors=new string[theColors.Length];
41         for(int i=0;i<theColors.Length;i++)
42         {
43             Colors[i]=theColors[i];
44         }
45     }
46 }

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

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

  

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

 

posted @ 2013-10-07 11:31  YoMe  阅读(2037)  评论(0编辑  收藏  举报