IEnumerable和IEnumerator详解
引言
IEnumerable是可枚举的所有非泛型集合的基接口, IEnumerable包含一个方法GetEnumerator(),该方法返回一个IEnumerator;IEnumerator提供通过Current属性以及MoveNext()和Reset()方法来循环访问集合的功能。
IEnumerable 接口
公开枚举数,该枚举数支持在非泛型集合上进行简单迭代。接口源码如下:
public interface IEnumerable { [DispId(-4), __DynamicallyInvokable] IEnumerator GetEnumerator(); }
IEnumerator 接口
支持对非泛型集合的简单迭代。接口源码如下:
public interface IEnumerator { [__DynamicallyInvokable] bool MoveNext(); [__DynamicallyInvokable] object Current { [__DynamicallyInvokable] get; } [__DynamicallyInvokable] void Reset(); }
举例说明
示例演示了通过实现IEnumerable和IEnumerator接口来循环访问自定义集合的最佳实践。
定义一个简单的实体类:
public class Person { public Person(string name, int age) { this.Name = name; this.Age = age; } public string Name; public int Age; }
定义一个实体类的集合,继承IEnumerate:
public class People : IEnumerable { private Person[] _people; public People(Person[] pArray) { _people = new Person[pArray.Length]; for (int i = 0; i < pArray.Length; i++) { _people[i] = pArray[i]; } } /// <summary> /// GetEnumerator方法的实现 /// </summary> /// <returns></returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }