IEnumerable
public interface IEnumerable
{
IEnumerator GetEnumerator();
}
IEnumerable非常简单,就一个GetEnumerator()
方法,但是这个方法的返回值却是一个IEnumerator
对象,从注释我们可以得知IEnumerable
代表继承此接口的类可以获取一个IEnumerator
来实现枚举
这个类中包含的集合中的元素的功能(比如List/ArrayList/Dictionary等继承了IEnumeratble接口的类)
IEnumerator
public interface IEnumerator
{
object Current { get; }
bool MoveNext();
void Reset();
}
IEnumerator有一个object类型的属性,还有一个返回值为bool值的MoveNext
方法和一个无返回值的Reset
方法
IEnumerator 与 IEnumerable使用的案例
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace dotnetLearn.集合学习
{
public class MyList : IEnumerable
{
public int[] _data = new int[10] { 1, 5, 7, 9, 7, 8, 7, 8, 7, 4 };
public int this[int index]
{
get
{
return _data[index];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
Console.WriteLine("foreach调用 GetEnumerator");
return new MIEnumtor(this);
}
}
public class MIEnumtor : IEnumerator
{
private MyList myList;
private int index;
public MIEnumtor(MyList my)
{
index = -1;
myList = my;
}
public object Current
{
get
{
Console.WriteLine("foreach调用 Current");
return myList[index];
}
}
public bool MoveNext()
{
Console.WriteLine("foreach调用 MoveNext");
if (index < myList._data.Length - 1)
{
index++;
return true;
}
index = -1;
return false;
}
public void Reset()
{
}
}
public class IEnumerator01
{
public void test()
{
MyList my = new MyList();
foreach (var item in my)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}
通过输出结果,我们可以发现,foreach在运行时会先调用MyList的GetIEnumerator函数获取一个MIEnumtor,之后通过循环调用MIEnumtor的MoveNext函数,index后移,更新Current属性,然后返回Current属性,直到MoveNext返回false。
区别
IEnumerable表示一个可枚举的集合,可以用 foreach 循环遍历,用于返回一个 IEnumerator(迭代器) 对象
IEnumerator 当一个类实现 IEnumerator 接口时,它表示该类提供了迭代集合的方法。