IEnumerable和IEnumerator 区别
IEnumerable 和 IEnumerator 需要引入using system.collection 程序集
IEnumerable 可枚举类实现IEnumerable 接口的类,IEnumerable类只有一个成员是GetEnumerator方法,该方法返回的是一个枚举器(IEnumerator)。
IEnumerator 接口的枚举器包含三个函数成员:Reset(方法),MoveNext(方法),Current(属性);
Current:属性 返回当前的位置的值
这是属性是只能的。
这个属性返回的是Object类型。可以返回任何类型。
MoveNext 方法 ,把枚举器位置前进到下一项的方法,如果新的位置有效则返回True,其他 返回false;
枚举器的原始位置是-1;所以需要在使Current之前调用一次该方法;
Reset 方法 重置枚举器。使枚举器的位置赋予初始值。
代码:
static void main()
{
int[] MyArray= {10,11,12,13}
//声明一个枚举器并赋值
IEnumerator ie= MyArray.GetEnumerator();
while(ie.MoveNext)
{
int i=(int)ie.Current;
Console.Write($"{i}");
}
console.readLinde();
}
//代码2 IEnumerable和IEnumerator一起使用
注:以上是非泛型版本的;通常使用的是泛型枚举接口IEnumerator和IEnumerable
区别:IEnumerable接口的GetEnumerator 返回一个枚举器类IEnumerator的实例;
IEnumerable接口的GetEnumerator 返回一个枚举器类IEnumerator的实例;
class Program
{
static void Main(string[] args)
{
Spectrum spectrum = new Spectrum();
foreach (string item in spectrum)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
class Spectrum:IEnumerable
{
string[] colors = { "Violte", "Blue", "Cyan", "Green", "yellow", "orange", "red" };
public IEnumerator GetEnumerator()
{
return new ColorEnumerator(colors);
}
}
class ColorEnumerator:IEnumerator
{
private string[] colors;
//位置
private 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;
}
}
注:以上是非泛型版本的;通常使用的是泛型枚举接口IEnumerator
区别:IEnumerable接口的GetEnumerator 返回一个枚举器类IEnumerator的实例;
IEnumerable
IEnumerator的属性Current 返回的是Object的引用。我们必须转换为实际类型的对象。
IEnumerator<T> 属性Current,返回的是实际类型的对象,不是Object的以用。

浙公网安备 33010602011771号