迭代器模式
The Iterator design pattern provides a way to acess the elements of an aggregate object sequentially without exposing its underlying representation.
迭代器模式提供了顺序访问聚合对象中元素的方式,而不需要暴露底层表示。
UML Class Diagram
Iterator; This is going to be an interface defining the operations for accessing and traversing elements in a sequence.
ConcreteIterator: This is going to be a concrete class implementing the Iterator interface and providing implementation for Iterator interface method. This class also keep track of the current position of the elment in the traversal.
Aggregate: This is going to be an interface that defines an operation to create an interator object.
ConcreteAgregate: This is going to be a conrecte class that implements the Aggreate interface to return an instance of the proper Conrete Itorator class i.e. an instance of the Iterator class.
Client:This is class that going to use the Iterator and Aggregate interface and access the elments.
Structure Code in C#

public interface IAggregate { IIterator CreateIterator(); } public class ConcreteAggregate : IAggregate { private List<object> items = new List<object>(); public IIterator CreateIterator() { return new ConcreteIterator(this); } public Int32 Count { get { return items.Count; } } public object this[Int32 index] { get { return items[index]; } set { items.Insert(index, value); } } }

public interface IIterator { object First(); object Next(); bool IsLast(); object CurrentItem(); } public class ConcreteIterator: IIterator { ConcreteAggregate aggregate; Int32 current = 0; public ConcreteIterator(ConcreteAggregate aggregate) { this.aggregate = aggregate; } public object First() { return aggregate[0]; } public object Next() { object next = null; if (current < aggregate.Count - 1) next = aggregate[++current]; return next; } public object CurrentItem() { return aggregate[current]; } public bool IsLast() { return current >= aggregate.Count; } }
Why do we need to use the Iterator Design Pattern in C#?
The Iterator Design Pattern in C# allows us to Access the elements of a collection wihout exposing its internal data structure. That means it allows you to navigate through a different collection of data using a common interface wihout knowing about their underlying implementation.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)