设计模式-迭代器模式

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

相关推荐
繁华似锦respect4 小时前
C++ unordered_map 底层实现与详细使用指南
linux·开发语言·c++·网络协议·设计模式·哈希算法·散列表
繁华似锦respect11 小时前
HTTPS 中 TLS 协议详细过程 + 数字证书/签名深度解析
开发语言·c++·网络协议·http·单例模式·设计模式·https
数智研发说11 小时前
智汇电器携手鼎捷PLM:从“制造”迈向“智造”,构建高效协同研发新范式
大数据·人工智能·设计模式·重构·制造·设计规范
繁华似锦respect12 小时前
Linux - KCP 协议深度解析:原理、与 TCP/UDP 的对比及应用场景
linux·tcp/ip·观察者模式·设计模式·udp
太阳以西阿13 小时前
【设计模式03】命令设计模式(行为型设计模式)
设计模式
太阳以西阿13 小时前
【设计模式02】策略设计模式(行为型设计模式)
设计模式
雨中飘荡的记忆13 小时前
设计模式之享元模式详解
java·设计模式·享元模式
Blossom.11813 小时前
基于多智能体协作的AIGC内容风控系统:从单点检测到可解释裁决链
人工智能·python·深度学习·机器学习·设计模式·aigc·transformer
Jomurphys13 小时前
设计模式 - 责任链模式 Chain of Responsibility Pattern
android·设计模式·责任链模式
雨中飘荡的记忆14 小时前
设计模式之桥接模式详解
设计模式·桥接模式