在C#中,可以通过实现IEnumerator
接口来创建一个性能与数组foreach
相当的IEnumerator
。下面是一个示例代码:
public class MyEnumerator : IEnumerator
{
private T[] _array;
private int _currentIndex;
public MyEnumerator(T[] array)
{
_array = array;
_currentIndex = -1;
}
// 实现IEnumerator接口的成员
public T Current
{
get
{
if (_currentIndex < 0 || _currentIndex >= _array.Length)
throw new InvalidOperationException();
return _array[_currentIndex];
}
}
object IEnumerator.Current => Current;
public bool MoveNext()
{
_currentIndex++;
return _currentIndex < _array.Length;
}
public void Reset()
{
_currentIndex = -1;
}
public void Dispose()
{
// 可选的资源清理代码
}
}
使用示例:
int[] array = { 1, 2, 3, 4, 5 };
MyEnumerator enumerator = new MyEnumerator(array);
while (enumerator.MoveNext())
{
int item = enumerator.Current;
Console.WriteLine(item);
}
enumerator.Dispose();
这个自定义的MyEnumerator
类实现了IEnumerator
接口,其中Current
属性返回当前位置的元素,MoveNext()
方法用于移动到下一个元素,Reset()
方法用于将位置重置到初始状态,Dispose()
方法用于释放资源。
使用这个自定义的MyEnumerator
类,可以像使用foreach
一样遍历数组中的元素,并且性能与foreach
相当。