IEnumerable是可枚舉的全部非泛型集合的基接口, IEnumerable包含一個方法GetEnumerator(),該方法返回一個IEnumerator;IEnumerator提供經過Current屬性以及MoveNext()和Reset()方法來循環訪問集合的功能。編程
公開枚舉數,該枚舉數支持在非泛型集合上進行簡單迭代。接口源碼以下:this
public interface IEnumerable { [DispId(-4), __DynamicallyInvokable] IEnumerator GetEnumerator(); }
支持對非泛型集合的簡單迭代。接口源碼以下:spa
public interface IEnumerator { [__DynamicallyInvokable] bool MoveNext(); [__DynamicallyInvokable] object Current { [__DynamicallyInvokable] get; } [__DynamicallyInvokable] void Reset(); }
示例演示了經過實現IEnumerable和IEnumerator接口來循環訪問自定義集合的最佳實踐。code
定義一個簡單的實體類:blog
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(); } public PeopleEnum GetEnumerator() { return new PeopleEnum(_people); } }
定義一個枚舉器,繼承IEnumerator:接口
public class PeopleEnum : IEnumerator { public Person[] _people; /// <summary> /// 枚舉器位於第一個元素以前直到第一個MoveNext()調用。 /// </summary> private int position = -1; public PeopleEnum(Person[] list) { _people = list; } public bool MoveNext() { position++; return position < _people.Length; } public void Reset() { position = -1; } object IEnumerator.Current => Current; public Person Current { get { try { return _people[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } }
具體調用:get
Person[] peopleArray = new Person[3] { new Person("張三", 15), new Person("李四", 18), new Person("王五", 21), }; People peopleList = new People(peopleArray); foreach (Person p in peopleList) Console.WriteLine(p.Name + "\t" + p.Age);
輸出:源碼
其中,上邊調用中foreach等價於string
IEnumerator enumeratorSimple = peopleList.GetEnumerator(); while (enumeratorSimple.MoveNext()) { Person p = enumeratorSimple.Current as Person; Console.WriteLine(p?.Name + "\t" + p?.Age); }
經過例子,能夠得出:
IEnumerable表明繼承此接口的類(好比ArrayList,IList,List<T>等)能夠獲取一個IEnumerator來實現枚舉這個類中包含的集合中的元素的功能,是 .NET Framework 中最基本的集合訪問器。在編程中,Lambda表達式經過Select()或者Where()返回的變量爲IEnumerate<T>,此時咱們能夠經過foreach遍歷。但願本文對你有所幫助,下一篇介紹Lambda中的Select和Where,感興趣的朋友能夠加關注,歡迎留言交流!