C#中的迭代器

枚举器和迭代器

使用foreach语句迭代遍历

int[] arr = { 9, 12, 43, 10, 6, 5 };
foreach(int e in arr) Console.WriteLine(e);

数组之所以这么可以做,原因是数组可以按需提供一个叫做枚举器的对象,枚举器可以依次返回请求数组中的元素。对于有枚举器的类型而言,必须有一种方式来获取它,获取对象枚举器的方法是调用对象的GEnumertaor方法。实现GetEnumeratot方法的类型可叫做可枚举类型enumerable type,其中数组是可枚举类型。

IEnumerator接口

实现了IEnumerator接口的枚举器包含了3个函数成员:Current、MoveNext、Rest:

  • Current是返回序列中当前位置项的属性。
  • MoveNext,把枚举器位置前进到集合的下一个位置,如果新的位置是有效的,返回true,否则(例如到达了尾部)无效。
  • Reset是把位置重置到原始状态的方法。
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
IEnumerator ie = arr.GetEnumerator();	// 获取枚举器
while (ie.MoveNext()) Console.WriteLine($"{ie.Current}");	// 获取当前项并输出

IEnumerable接口

可枚举类是指实现了IEnumerable接口的类,IEnumerable接口只有一个成员GetEnumerator方法,它返回对象的枚举器,例如下面的例子:

using System.Collections;

namespace CSharpProject1;

class MyColor : IEnumerable
{
    private string[] Colors = { "RED", "YELLOW", "BLUE" };
    public IEnumerator GetEnumerator()
    {
        return new ColorEnumerator(Colors);
    }
}

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

    public ColorEnumerator(string[] colors)
    {
        this.colors = new string[colors.Length];
        for (int i = 0; i < colors.Length; i++) this.colors[i] = colors[i];
    }
    
    public bool MoveNext()
    {
        if (position < this.colors.Length - 1)
        {
            position++;
            return true;
        }
        else return false;
    }

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

    public object Current
    {
        get
        {
            if (position == -1) throw new InvalidCastException();
            if (position > this.colors.Length) throw new InvalidOperationException();
            return colors[position];
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyColor mc = new MyColor();
        foreach (string color in mc) Console.WriteLine(color);
    }
}
D:/RiderProjects/CSharpProject1/CSharpProject1/bin/Debug/net8.0/CSharpProject1.exe
RED
YELLOW
BLUE  

Process finished with exit code 0.

迭代器

迭代器是更先进的枚举器:

using System.Collections;

namespace CSharpProject1;

class MyClass
{
    public IEnumerator<string> GetEnumerator()
    {
        return BlackAndWhite(); // 返回迭代器
    }

    public IEnumerator<string> BlackAndWhite()  //迭代器
    {
        yield return "black";
        yield return "gray";
        yield return "white";
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass mc = new MyClass();
        foreach (string e in mc) Console.WriteLine($"{e}");
    }
}
posted @ 2024-01-16 12:26  LilyFlower  阅读(7)  评论(0编辑  收藏  举报