设计模式-迭代器模式

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

相关推荐
GISer_Jing10 分钟前
AI:多智能体协作与记忆管理
人工智能·设计模式·aigc
雨中飘荡的记忆2 小时前
责任链模式实战应用:从理论到生产实践
设计模式
沛沛老爹5 小时前
Web开发者进阶AI:Agent技能设计模式之迭代分析与上下文聚合实战
前端·人工智能·设计模式
Geoking.6 小时前
【设计模式】装饰者模式详解
设计模式·装饰器模式
vx-bot5556667 小时前
企业微信接口在自动化工作流中的关键角色与设计模式
设计模式·自动化·企业微信
Yu_Lijing8 小时前
基于C++的《Head First设计模式》笔记——工厂模式
c++·笔记·设计模式
HL_风神1 天前
设计原则之迪米特
c++·学习·设计模式
HL_风神1 天前
设计原则之合成复用
c++·学习·设计模式
Aeside11 天前
揭秘 Nginx 百万并发基石:Reactor 架构与 Epoll 底层原理
后端·设计模式
帅气的你1 天前
从零封装一个通用的 API 接口返回类:统一前后端交互格式
java·设计模式