实现了IEnumerator接口的类称为枚举器
using System.Runtime.InteropServices;
namespace System.Collections
{
//
// 摘要:
// 支持对非泛型集合的简单迭代。
[ComVisible(true)]
[Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")]
public interface IEnumerator
{
//
// 摘要:
// 获取集合中的当前元素。
//
// 返回结果:
// 集合中的当前元素。
object Current { get; }
//
// 摘要:
// 将枚举数推进到集合的下一个元素。
//
// 返回结果:
// 如果枚举数已成功地推进到下一个元素,则为 true;如果枚举数传递到集合的末尾,则为 false。
//
// 异常:
// T:System.InvalidOperationException:
// 创建枚举器后,已修改该集合。
bool MoveNext();
//
// 摘要:
// 将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。
//
// 异常:
// T:System.InvalidOperationException:
// 创建枚举器后,已修改该集合。
void Reset();
}
}
using System;
using System.Collections;
namespace 枚举器
{
class Program
{
static void Main()
{
int[] myArray = { 10, 11, 12, 13 };
IEnumerator ie = myArray.GetEnumerator();
while (ie.MoveNext())
{
int i = (int)ie.Current;
Console.WriteLine(i);
}
}
}
}
1、数组可以按需提供一个枚举器的对象
2、枚举器实现了IEnumerator接口,所以它能做IEnumerator接口定义的所有工作
3、对于有枚举器的类型而言,必须有一个方法来获取它,获取一个对象枚举器的方法是调用对象的GetEnumerator方法,实现GetEnumerator方法的类型叫做可枚举类型(enumerable),数组是可枚举类型
所以在此案例中,采用GetEnumerator()方法将获取到的数组的枚举器赋值给定义为枚举器类型的ie,GetEnumerator()方法获取到的是返回的枚举器的实例
调用方法时MoveNext要在前,Current方法在后。否则会出现枚举器还处于数组序列中第一项之前时,便先要输出的Current值,结果错误。它们的次序问题我们将通过下个综合实例观察
using System.Runtime.InteropServices;
namespace System.Collections
{
//
// 摘要:
// 公开枚举数,该枚举数支持在非泛型集合上进行简单迭代。若要浏览此类型的.NET Framework 源代码,请参阅 Reference Source。
[ComVisible(true)]
[Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]
public interface IEnumerable
{
//
// 摘要:
// 返回循环访问集合的枚举数。
//
// 返回结果:
// 一个可用于循环访问集合的 System.Collections.IEnumerator 对象。
[DispId(-4)]
IEnumerator GetEnumerator();
}
}
可枚举类是指实现了IEnumerable接口的类,IEnumearable接口只有一个成员GetEnumerator方法,它返回对象的枚举器
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 IEnumerator 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
请按任意键继续. . .
*/
大家还有什么问题,欢迎在下方留言!