说明:在软件构建过程中,集合对象内部结构常常变化各异。但对于这些集合对象,我们希望在不暴露其内部结构的同时,
可以让外部客户代码透明地访问其中包含的元素;同时这种“透明遍历”也为“同一种算法在多种集合对象上进行操作”
提供了可能。使用面向对象技术将这种遍历机制抽象为“迭代器对象”为“应对变化中的集合对象”提供了一种优雅的方式
这种设计模式已经内化为C#语言的一种元素了,就是Foreach关键字.顺便吐槽一下,高级语言封装的太狠,很多东西许多
程序员都不了解本质就把功能实现了.结果作开发了几年,发现自己技术提高不上去了,一些必要的知识我们还是需要关注.
类图:

代码:
public class Enumerator : IEnumerator
{
int index = -1;
private TableCollection _collection;
public Enumerator(TableCollection collection)
{
_collection = collection;
}
public object Current
{
get {
return _collection.items[index];
}
}
public bool MoveNext()
{
index++;
return (index < _collection.items.GetLength(0));
}
public void Reset()
{
index = -1;
}
}
public class TableCollection : IEnumerable
{
public int[] items;
public TableCollection()
{
items = new int[] { 1, 2, 3, 5, 6, 7, 8, 9, 10 };
}
public IEnumerator GetEnumerator()
{
return new Enumerator(this);
}
}
class Program
{
static void Main(string[] args)
{
int sum = 0;
TableCollection col = new TableCollection();
IEnumerator ietor = col.GetEnumerator();
ietor.Reset();
while (ietor.MoveNext())
{
int i = (int)ietor.Current;
sum += i;
}
Console.WriteLine(sum.ToString());
}
}
浙公网安备 33010602011771号