IEnumerable接口
可枚举类是指实现了IEnumerable接口的类。IEnumerable接口只有一个成员—GetEnumerator
方法,它返回对象的枚举器。
图19-5演示了一个有3个枚举项的类MyClass,通过实现GetEnumerator方法来实现.IEnumerable
接口。
如下代码演示了可枚举类的声明形式:
using System.Collections;
class MyClass:IEnumerable //实现IEnumerable接口
{
public IEnumerable GetEnumerator{....} //返回IEnumerator类型的对象
}
下面的代码给出了一个可枚举类的示例,使用实现了IEnumerator的枚举器类CoIorEnumerator。
我们将在下一节展示ColorEnumerator的实现。
使用IEnumerabIe和IEnumerator的示例
下面的代码展示了一个可枚举类的完整示例,该类叫作Spectrum,它的枚举器类为Color-
Enumerator。Program类在Main方法中创建了一个spectrum实例,并用于foreach循环。
using System;
using System.Collections;
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 Spectrum:IEnumerable
{
string [] Colors={"violet","blue","cyan","green","yellow","orange","red"};
public IEnumerable GetEnumerator()
{
return new ColorEnumerator(Colors);
}
}
class Program
{
static void Main()
{
Spectrum spectrum=new Spectrum();
foreach(string color in spectrum)
Console.WriteLine(color);
}
}
这段代码产生了如下的输出:
violet
blue
cyan
green
yellow
orange
red