设计模式-迭代器模式

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

相关推荐
Zane199415 小时前
同一段单例代码,为什么在高并发下偶尔会创建出两个实例?聊聊哪种单例实现才是真的安全
设计模式
Carl_奕然15 小时前
【智能体】Loop 的四种设计模式之:Agent Loop(2026 最新版)
人工智能·设计模式·语言模型
小酒星小杜16 小时前
画 AI 漫画,别只会写“日漫风”:10 种画风、适用故事和可复制提示词
人工智能·设计模式·程序员
sarasuki1 天前
为什么 Agent 工具需要一个「协议」而不是「框架」:MCP 成为标准的底层逻辑
设计模式·agent·mcp
vivo互联网技术1 天前
知识不是文件,也不是向量 | KDC 系列 02
人工智能·设计模式·架构
Zane19947 天前
一个 new 就能创建对象,为什么还要拆出单例、工厂、建造者、原型四种模式?
设计模式
怕浪猫8 天前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane19948 天前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19949 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..9 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot