对象要实现可以迭代需IEnumerable接口并实现GetEnumerator方法。一下简单例子
public class SPEnumerable<T> : IEnumerable
{
private T[] array; public SPEnumerable()
{
array = new T[];
} public void Add(T item)
{
Array.Resize<T>(ref array, array.Length + );
array[array.Length - ] = item;
} #region IEnumerable 成员 IEnumerator IEnumerable.GetEnumerator()
{
foreach (T item in array)
{
yield return item;
}
} #endregion
}
当然也可以自己去实现IEnumerator接口
public class SPEnumerable<T> : IEnumerable
{
private T[] array; public SPEnumerable()
{
array = new T[];
} public void Add(T item)
{
Array.Resize<T>(ref array, array.Length + );
array[array.Length - ] = item;
} #region IEnumerable 成员 IEnumerator IEnumerable.GetEnumerator()
{
return new SPEnumerator<T>(array);
} #endregion
} public class SPEnumerator<T> : IEnumerator
{
private int position = -;
private T[] array; public SPEnumerator(T[] array)
{
this.array = array;
} #region IEnumerator 成员 public object Current
{
get
{
return array[position];
}
} public bool MoveNext()
{
position++;
return position < array.Length;
} public void Reset()
{
position = -;
} #endregion
}