代码中如何返回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()
{
//关键,必须实现的方法,返回为IEnumerator接口类型,为枚举数对象.通过它来实现另外的3个方法。
return new ColorEnumerator(Colors);//传入的参数为,本类的变量。
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("按任意键结束...");
Console.ReadKey();
}
}
}
以上是源代码,请问return new ColorEnumerator(Colors);这行代码中如何返回IEnumerator?谢谢!
[解决办法]
class ColorEnumerator : IEnumerator
--第二个类你实现接口出错了.
IEnumberable和IEnumberator是两个不同的接口.