设计模式-迭代器模式

在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循环来迭代集合中的元素。

相关推荐
AI人工智能+电脑小能手16 小时前
大白话说Java设计模式-42-访问者模式(业务实战篇)
java·spring·设计模式·访问者模式·asm·营销规则·数据结构与操作分离
AI人工智能+电脑小能手17 小时前
大白话说Java设计模式-43-访问者模式(源码剖析篇)
java·设计模式·访问者模式·源码分析·elementvisitor·asm classvisitor·spring spel
Michael_lcf1 天前
Agent设计模式:思考-行动-观察循环的本质与局限
设计模式·agent设计模式·agent设计模式的本质
丰锋ff1 天前
设计模式学习笔记
笔记·学习·设计模式
米啦啦.1 天前
设计模式/
观察者模式·单例模式·设计模式·工厂模式
QuZhengRong1 天前
【AI】Agent 全栈进阶|Agent 设计模式
人工智能·学习·设计模式·llm·agent
码匠许师傅1 天前
【设计模式精讲】2. 设计原则基石:SOLID 与几条关键原则
java·设计模式·log4j
AI人工智能+电脑小能手2 天前
大白话说Java设计模式-41-备忘录模式(源码剖析篇)
java·设计模式·备忘录模式·源码分析·serializable·undo log·spring statemachine
yinchnag2 天前
CRTP:奇异递归模板模式在 Go 模块系统中的实现
设计模式·go
AI人工智能+电脑小能手2 天前
大白话说Java设计模式-40-备忘录模式(业务实战篇)
java·设计模式·事务回滚·备忘录模式·状态保存·spring transactional·购物车快照