设计模式-迭代器模式

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

相关推荐
pan_junbiao8 分钟前
Spring框架的设计模式
java·spring·设计模式
蔡蓝13 小时前
设计模式-建造者模式
服务器·设计模式·建造者模式
不伤欣18 小时前
游戏设计模式 - 子类沙箱
游戏·unity·设计模式
漫谈网络18 小时前
MVC与MVP设计模式对比详解
设计模式·mvc
蔡蓝18 小时前
设计模式-观察着模式
java·开发语言·设计模式
哆啦A梦的口袋呀20 小时前
基于Python学习《Head First设计模式》第六章 命令模式
python·学习·设计模式
半路下车1 天前
【Harmony OS 5】HarmonyOS应用测试指南
设计模式·harmonyos
周某某~1 天前
一.设计模式的基本概念
设计模式
on the way 1231 天前
行为型设计模式之Interpreter(解释器)
设计模式
cui_hao_nan1 天前
设计模式——模板方法
java·设计模式