C#枚举器/迭代器

一、枚举器

  1、为什么foreach可以顺序遍历数组?

  因为foreach可以识别可枚举类型,通过访问数组提供的枚举器对象来识别数组中元素的位置从而获取元素的值并打印出来。

  2、什么是枚举器?可枚举类型?

  枚举结构里元素都是默认排序的,可以依靠识别元素的位置来获取值。可以把枚举器看做是集合的一个方法对象,他可以

  依次返回所有的元素。而诸如此类给元素排好序的集合类型都可以算作可枚举类型。

  3、具体过程如何实现?

  

 

 

二、可枚举类

  枚举器继承了IEnumerable接口,包含了三个函数成员:Current、MoveNext、Reset。

  

 

 

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

复制代码
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 // 实现Current
    {
        get
        {
            if (_position == -1 )
                throw new InvalidOperationException();
            if (_position >= _colors.Length )
                throw new InvalidOperationException();
            return _colors[_position];
        }
    }
    
    public bool MoveNext() // 实现MoveNext
    {
        if ( _position < _colors.Length - 1 )
        {
            _position ++;
            return true;
        }
        else
            return false;
    }
    
    public void Reset() // 实现Reset
    {
        _position = -1;
    }
}

class Spectrum : IEnumerable
{
    string[] Colors = { "violet", "blue", "cyan", "green","yellow", "orange", "red" };
    
    public IEnumerator CetEnumerator()
    {
        return new ColorEnumerator( Colors );
    }
}

class Program
{
    static void Main()
    {
        Spectrum spectrum = new Spectrum();
        
        foreach( string color in spectrum )
            Console.Writeline( color );
    }
}
复制代码

三、迭代器

  一种便捷方式来创建枚举器跟迭代器,省略了手动编码实现可枚举类型跟枚举器。

  常用的迭代器模式有两种:

1、不实现GetEnumerator方法,直接调用迭代器方法。

复制代码
class Spectrum
{
    string[] colors ={ "violet", "blue", "cyan”, “green", "yellow", "orange", "red" };

                           // 返回一个可枚举类型
    public IEnumerable<string> UVtoIR()
    {
        for ( int i = 0; i < colors.Length; i++)
            yield return colors[i]);
    }
                        // 返回一个可枚举类型
    public IEnumerable<string> IRtoU()
    {
        for ( int i = colors.Length -1; i >= 0; i--)
            yleld return colors[i];
    }
}

class Program
{
    static void Main()
    {
        Spectrum spectrum = new Spectrum();

        foreach ( string color in spectrum.UVtoIR())
            Console.Write("{0}",color );
        Console.WriteLine();
        
        foreach ( string color in spectrum.IRtoUV())
            Console.Write("{O}",color );
        Console.Writeline();
    }
}
复制代码

 

2、实现GetEnumerator方法,让类可枚举,调用迭代器的时候会自动生成IEnumerable的类实例

复制代码
class Spectrum
{
    bool _listFromUVtoIR;
    string[] colors = { "violet", "blue", "cyan", "green","yellow", "orange", "red");

    public Spectrum( bool listFromVtoIR )
    {
        _listFromlVtoIR = listFromUVtoIR;
    }
    
    public IEnumerator<string> GetEnumerator()
    {
        return _listFromlVtoIR ? UVtoIR : IRtoUV;
    }
    
    public IEnumerator<string> UVtoIR
    {
        get
        {
            for ( int i = 0; i < colors.Length; i++ )
                yield return colors[i];
        }
    }

    public IEnumerator<string> IRtoUV
    {
        get
        {
            for ( int i = colors.Length - 1; i >= 0; i--)
                yield return colors[i];
        }
    }
}

class Program
{
    static void Main()
    {
        Spectrum startUV = new Spectrum( true );
        Spectrum startIR = new Spectrum( false );
        
        foreach ( string color in startuV )
            Console.Write("{0}", color );
        Console.Writeline();
        
        foreach ( string color in startIR )
            Console.Write("{0}", color );
        Console.WriteLine();
    }
}
复制代码

 

posted @   Darius丶段  阅读(180)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示