代码中如何返回IEnumerator?
using System;
using System.Collections;
namespace ConsoleTest
{
class ColorEnumerator : IEnumerable
{
string[] Colors;//实现IEnumerator
int Position = -1;
public object Current
{
get
{
if (Position == -1)
throw new InvalidOperationException();
if (Position == Colors.Length)
throw new InvalidOperationException();
return Colors[Position];
}
}
public bool MoveNext()
{
if (Position < Colors.Length - 1)
{
Position++;
return true;
}
else
return false;
}
public void Reset() { Position = -1; }
public ColorEnumerator(string[] theColors)//构造函数
{
Colors = new string[theColors.Length];
for (int i = 0; i < theColors.Length; i++)
Colors[i] = theColors[i];
}
}
class MyColors : IEnumerable
{
//必须实现IEnumerable接口和实现方法,定义此类型为可枚举类型。
string[] Colors = new string[3] { "Red", "Yellow", "Blue" }; //定义一个string数组
public IEnumerator GetEnumerator()
{