C# 枚举器和迭代器(IEnumerable接口)

IEnumerable接口

可枚举类是指实现了IEnumerable接口的类。IEnumerable接口只有一个成员—GetEnumerator
方法,它返回对象的枚举器。

图19-5演示了一个有3个枚举项的类MyClass,通过实现GetEnumerator方法来实现.IEnumerable
接口。

GetEnumerator方法返回类的一个枚举器对象

如下代码演示了可枚举类的声明形式:

using System.Collections;

class MyClass:IEnumerable //实现IEnumerable接口
{
    public IEnumerable GetEnumerator{....}  //返回IEnumerator类型的对象
}

下面的代码给出了一个可枚举类的示例,使用实现了IEnumerator的枚举器类CoIorEnumerator。
我们将在下一节展示ColorEnumerator的实现。

使用IEnumerabIe和IEnumerator的示例
下面的代码展示了一个可枚举类的完整示例,该类叫作Spectrum,它的枚举器类为Color-
Enumerator。Program类在Main方法中创建了一个spectrum实例,并用于foreach循环。

using System;
using System.Collections;

class ColorEnumerator:IEnumerator
{
    string[] colors;
    int position=-1;

    public ColorEnumerator(string[] theColors)
    {
        colors=new string[theColors.Length];
        for(int i=0;i<theColors.Length;i++)
            colors[i]=theColors[i];
    }

    public object Current
    {
        get
        {
            if(position==-1)
                throw new InvalidOperationException();
            if(position>=_colors.Length)
                throw new InvalidOperationException();

            return colors[position];
        }
    }

    public bool MoveNext()
    {
        if(position<_colors.Length-1)
        {
            position++;
            return true;
        }
        else
            return false;
    }

    public void Reset()
    {
        position=-1;
    }
}

class Spectrum:IEnumerable
{
    string [] Colors={"violet","blue","cyan","green","yellow""orange","red"};

    public IEnumerable GetEnumerator()
    {
        return new ColorEnumerator(Colors);
    }
}

class Program
{
    static void Main()
    {
        Spectrum spectrum=new Spectrum();
        foreach(string color in spectrum)
            Console.WriteLine(color);
    }
}

这段代码产生了如下的输出:

violet 
blue 
cyan 
green 
yellow 
orange 
red
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

钢铁男儿

赛博功德充值,BUG退散

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值