zoukankan      html  css  js  c++  java
  • 【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 }
  • 相关阅读:
    团队项目——技术规格说明书
    Scrum Meeting 11.1
    Scrum Meeting 10.31
    Scrum Meeting 10.30
    Scrum Meeting 10.29
    Scrum Meeting 10.28
    Scrum Meeting 10.27
    Scrum Meeting 10.26
    团队作业Week5
    Boost C++: 数据结构---tuple
  • 原文地址:https://www.cnblogs.com/wywnet/p/3355170.html
Copyright © 2011-2022 走看看