关于C#枚举数的问题
程序代码:class ColorEnumerator : IEnumerator//定义的枚举类
{
string[] Colors;
int Position = -1;
public ColorEnumerator(string[] theColors)
{
Colors = new string[theColors.Length];
for (int i = 0; i < theColors.Length;i++ )
{
Colors[i] = theColors[i];
}
}
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;
}
}
class MyColors : IEnumerable
{
string[] Colors = { "red", "yellow", "blue" };
public IEnumerator GetEnumerator()
{
return new ColorEnumerator(Colors);
}
}
static void Main(string[] args)
{
{
MyColors my = new MyColors();
foreach (string color in my)//在这里,使用foreach为什么会调用MyColors类中的GetEnumerator方法啊?而进入ColorEnumerator类中方法的调用顺序又是怎么一回事啊?
{
Console.WriteLine(color);
}
Console.ReadKey();
}
} 另外C#中要实现枚举数则IEnumerable和IEnumerator是不是要成对出现?枚举数的实现是不是依赖于这两个接口啊?








