设计模式-迭代器模式

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

相关推荐
ikkkkkkkl3 小时前
C++设计模式:面向对象设计原则
c++·设计模式·面向对象
whitepure7 小时前
万字详解Java中的面向对象(二)——设计模式
java·设计模式
稚辉君.MCA_P8_Java9 小时前
豆包 Java的23种设计模式
java·linux·jvm·设计模式·kubernetes
快乐的划水a19 小时前
组合模式及优化
c++·设计模式·组合模式
Zyy~20 小时前
《设计模式》装饰模式
java·设计模式
落霞的思绪1 天前
Java设计模式详细解读
java·开发语言·设计模式
是2的10次方啊1 天前
🚀 JDK设计模式大揭秘:23种模式藏在你每天在用的类里
设计模式
步行cgn1 天前
设计模式(Design Patterns)
设计模式
Zyy~1 天前
《设计模式》代理模式
设计模式·代理模式
o0向阳而生0o1 天前
93、23种设计模式之抽象工厂模式
设计模式·抽象工厂模式