IEnumerable 接口
公开枚举器,该枚举器支持在非泛型集合上进行简单迭代。
命名空间: System.Collections
程序集: mscorlib(在 mscorlib.dll 中)
IEnumerable 类型公开以下成员。
| 名称 | 说明 | |
|---|---|---|
![]() |
GetEnumerator | 返回一个循环访问集合的枚举数。 |
| 名称 | 说明 | |
|---|---|---|
![]() |
AsParallel | 启用查询的并行化。 (由 ParallelEnumerable 定义。) |
![]() |
AsQueryable | 将 IEnumerable 转换为 IQueryable。 (由 Queryable 定义。) |
![]() |
Cast<TResult> | 将 IEnumerable 的元素转换为指定的类型。 (由 Enumerable 定义。) |
![]() |
OfType<TResult> | 根据指定类型筛选 IEnumerable 的元素。 (由 Enumerable 定义。) |
有关此接口的泛形版本,请参见 System.Collections.Generic.IEnumerable<T>。
对实现者的说明
必须实现 IEnumerable 以支持 Microsoft Visual Basic 的 foreach 语义。 允许枚举数的 COM 类也实现此接口。
下面的代码示例演示如何实现自定义集合的 IEnumerable 和 IEnumerator 接口。 在此示例中,没有显式调用这些接口的成员,但实现了它们,以便支持使用 foreach(在 Visual Basic 中为 For Each)循环访问该集合。
using System; using System.Collections; public class Person { public Person(string fName, string lName) { this.firstName = fName; this.lastName = lName; } public string firstName; public string lastName; } 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]; } } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator) GetEnumerator(); } public PeopleEnum GetEnumerator() { return new PeopleEnum(_people); } } public class PeopleEnum : IEnumerator { public Person[] _people; // Enumerators are positioned before the first element // until the first MoveNext() call. 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 { get { return Current; } } public Person Current { get { try { return _people[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } } class App { static void Main() { Person[] peopleArray = new Person[3] { new Person("John", "Smith"), new Person("Jim", "Johnson"), new Person("Sue", "Rabon"), }; People peopleList = new People(peopleArray); foreach (Person p in peopleList) Console.WriteLine(p.firstName + " " + p.lastName); } } /* This code produces output similar to the following: * * John Smith * Jim Johnson * Sue Rabon * */



浙公网安备 33010602011771号