设计模式-迭代器模式

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

相关推荐
Doris_20239 小时前
代码格式化 使用oxfmt
设计模式·架构·前端框架
Doris_20239 小时前
说一说ESLint+Prettier生效的原理
前端·设计模式·架构
Pomelooooo10 小时前
把 git commit 这件事,彻底交给 AI ——一个工程化 /git-commit 命令的设计与落地
设计模式
invicinble12 小时前
设计模式(类的拓扑结构)(描述总纲)
设计模式·原型模式
invicinble14 小时前
设计模式(类的拓扑结构)(为什么会产生设计模式,以及什么是设计模式)
linux·服务器·设计模式
PersonalViolet16 小时前
模板方法模式实战:重构Agent工具审批,告别重复代码
设计模式·agent
老码观察17 小时前
设计模式实战解读(五):策略模式——干掉 if-else 的优雅方案
java·设计模式·策略模式
解决问题no解决代码问题17 小时前
设计模式分类介绍
java·开发语言·设计模式
烬羽17 小时前
从 Python List 到 LLM 接口:一条被忽视的 AI 入门捷径
设计模式
我爱cope18 小时前
【Agent智能体8 | 反思设计模式-大语言模型反思机制的四个演进阶段】
人工智能·设计模式·语言模型