代码中如何返回IEnumerator?

zcw1967 zcw1967 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
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?谢谢!
...全文

相关推荐

评论 10
收藏 已收藏
分享
返回顶部
zcw1967
C# 111,130 成员 642,540 内容