C# IEnumerable和IEnumerator的区别,如何实现
IEnumerable接口和IEnumerator接口是.NET中非常重要的接口,二者有何区别?
1. 简单来说IEnumerable是一个声明式的接口,声明实现该接口的类就是“可迭代的enumerable”,但并没用说明如何实现迭代器(iterator).其代码实现为:
public interface IEnumerable
{
IEnumerator GetEnumerator();
}
2. 而IEnumerator接口是实现式接口,它声明实现该接口的类就可以作为一个迭代器iterator.其代码实现为:
public interface IEnumerator
{
object Current { get; }
bool MoveNext();
void Reset();
}
3.一个collection要支持Foreach进行遍历,就必须实现IEnumerable,并一某种方式返回迭代器对象:IEnumerator.
那么又如何实现这两个接口呢? 其代码如下:
假设有一个Person类,其有两个属性FirstName和LastName
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Person(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
}
另外通过People类来实现IEnumerable和IEnumerator接口.
//实现IEnumerable接口
public class People :IEnumerable
{
public Person [] pers;
public People(Person [] ps)
{
this.pers = ps;
}
public IEnumerator GetEnumerator()
{
//foreach(Person p in pers)
// {
// yield return p;
// }
return new People1(pers);
}
}
//实现IEnumerator接口
public class People1 : IEnumerator
{
public Person[] pers;
public People1(Person[] per)
{
this.pers = per;
}
int position = -1;
public bool MoveNext()
{
position++;
return position < pers.Length;
}
public void Reset()
{
position=-1;
}
public object Current
{
get
{
try
{
return pers[position];
}
catch(IndexOutOfRangeException ex)
{
throw new InvalidOperationException();
}
}
}
}