一、答案
能用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());
}