一、答案
能用foreach遍历访问的对象需要实现IEnumerable接口或声明GetEnumerator方法的类型
注:不一定要实现IEnumerable接口,但一定要实现GetEnumrator方法。
二、.Net 1.0实现
public class MyList<T> : IEnumerable
{
public int Count { get { return Items == null ? 0 : Items.Length; } }
public T[] Items { get; set; }
public T this[int index]
{
get { return Items[index]; }
}
//返回一个循环访问集合的枚举数。
public IEnumerator GetEnumerator()
{
return new MyEnumerator<T>() { List = this };
}
}
public class MyEnumerator<T> : IEnumerator
{
private int index = -1;
public MyList<T> List { get; set; }
//将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。
public void Reset()
{
index = -1;
}
//将枚举数推进到集合的下一个元素。
public bool MoveNext()
{
index++;
return (index < List.Count);
}
//获取集合中的当前元素。
public object Current { get { return List[index]; } }
}
//客户端调用,注:1.0中无泛型
MyList<int> list = new MyList<int>() { Items = new int[] { 1, 2, 3, 4 } };
foreach (int item in list)
{
MessageBox.Show(item.ToString());
}