• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

声明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 }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
c#格式化数字与日期发布时间:2022-07-13
下一篇:
给热爱学习的同学们推荐一些顶级的c# Blogs链接发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap