设计模式-迭代器模式

在C#中实现迭代器模式,你可以使用IEnumerable接口和IEnumerator接口。以下是一个简单的实现示例:

cs 复制代码
using System.Collections;
 
public class MyCollection : IEnumerable
{
    private readonly int[] items = { 1, 2, 3, 4, 5 };
 
    public IEnumerator GetEnumerator()
    {
        return new MyEnumerator(this);
    }
 
    public class MyEnumerator : IEnumerator
    {
        private readonly MyCollection _collection;
        private int index = -1;
 
        public MyEnumerator(MyCollection collection)
        {
            _collection = collection;
        }
 
        public object Current => _collection.items[index];
 
        public bool MoveNext()
        {
            index++;
            return index < _collection.items.Length;
        }
 
        public void Reset()
        {
            index = -1;
        }
 
        public void Dispose()
        {
            // 清理代码,如果有必要的话
        }
    }
}
 
// 使用示例
public class Program
{
    public static void Main()
    {
        MyCollection myCollection = new MyCollection();
        foreach (int item in myCollection)
        {
            System.Console.WriteLine(item);
        }
    }
}

这个示例中,MyCollection类实现了IEnumerable接口,并且提供了一个GetEnumerator方法,该方法返回一个MyEnumerator类的实例,这个类实现了IEnumerator接口。MyEnumerator类用来迭代集合中的元素。在Main方法中,我们创建了MyCollection的实例,并使用foreach循环来迭代集合中的元素。

相关推荐
花椒技术11 小时前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播
艺艺生辉19 小时前
迭代器模式-"我也想被增强for循环"
设计模式
咖啡八杯2 天前
GoF设计模式——策略模式
java·后端·spring·设计模式
槑有老呆4 天前
别再手搓 Prompt 了,那个叫"手动挡循环"
设计模式
用户6919026813395 天前
Vibe Coding 开发项目的基本范式
人工智能·设计模式·代码规范
怕浪猫5 天前
领域特定语言(Domain-Specific Language, DSL)
设计模式·程序员·架构
Larcher7 天前
AI Loop:让AI像人一样自主完成任务的核心机制
javascript·人工智能·设计模式
咖啡八杯8 天前
GoF设计模式——享元模式
java·spring·设计模式·享元模式