下面是一個簡易的實現代碼:
/// <summary>
/// 集合的接口
/// </summary>
public interface ICollection
{
int Count { get; }
/// <summary>
/// 獲取迭代器
/// </summary>
/// <returns>迭代器</returns>
Iterator GetIterator();
}
/// <summary>
/// 迭代器接口
/// </summary>
public interface Iterator
{
bool MoveNext();
object Current { get; }
}
public class List : ICollection
{
private const int MAX = 10;
private object[] items;
public List()
{
items = new object[MAX];
}
public object this[int i]
{
get { return items[i]; }
set { this.items[i] = value; }
}
#region ICollection Members
public int Count
{
get { return items.Length; }
}
public Iterator GetIterator()
{
return new ListIterator(this);
}
#endregion
}
public class ListIterator : Iterator
{
private int index = 0;
private ICollection list;
public ListIterator(ICollection list)
{
this.list = list;
index = 0;
}
#region Iterator Members
public bool MoveNext()
{
if (index + 1 > list.Count)
return false;
else
{
index++;
return true;
}
}
public object Current
{
get { return list[index]; }
}
#endregion
}
/// <summary>
/// 測試
/// </summary>
public class Program
{
static void Main()
{
ICollection list = new List();
Iterator iterator = list.GetIterator();
while (iterator.MoveNext())
{
object current = iterator.Current;
}
}
}