摘要:迭代器是C#2.0中添加的功能,它能够使我们在类或结构中支持foreach迭代,而不必实现整个IEnumerable/IEnumerable接口。今天我们就一块看一下什么是c#中的迭代器吧。
主要内容:
1.foreach的运行机制
2.传统集合的遍历
3.使用迭代器
一、foreach的运行机制
我们在程序中经常会用到foreach,如果你把它理解成是for的一种简写形式的话那就太大材小用了,事实上foreach中包含了丰富的内容。我们知道要使用foreach遍历集合就必须实现IEnumerable接口,而要实现IEnumerable接口就要实现IEnumerator接口。关于如何实现这两个接口我们在第二部分会看到,在谈foreach的运行机制之前请允许我使用msdn中的Person类(我们下面的几部分中我们还会用到相关的People和PeopleEnum类):
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace IteratorDemo
- {
- class Person
- {
- public Person(string fName, string lName)
- {
- this.firstName = fName;
- this.lastName = lName;
- }
- public string firstName;
- public string lastName;
- }
- }
当然具体细节我就不再说了,有了上面的Person类我们就可以运行下面的代码了:
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace IteratorDemo
- {
- class Program
- {
- static void Main(string[] args)
- {
- Person[] persons = new Person[] {
- new Person("Kenshin","Cui"),
- new Person("Miaoer","Sun"),
- new Person("Jinjuan","Shen"),
- new Person("Yanxin","Nie")
- };
- foreach (Person p in persons)
- {
- Console.WriteLine(p.firstName + " " + p.lastName);
- }
- Console.Read();
- }
- }
- }
具体的运行结果也没有什么可说的,可是为什么会有这样的结果呢?原因可以分两层来解释:第一就是我们的Persons是使用[]符号声明,这是一个Array类的记号。而Array类实现了IEnumerable接口中GetEnumerator()方法,因此它可以使用foreach进行迭代;第二,之所以实现IEnumerable接口的GetEnumerator()方法就能够迭代是因为foreach将上面的代码解析成如下的形式:
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace IteratorDemo
- {
- class Program
- {
- static void Main(string[] args)
- {
- Person[] persons = new Person[] {
- new Person("Kenshin","Cui"),
- new Person("Miaoer","Sun"),
- new Person("Jinjuan","Shen"),
- new Person("Yanxin","Nie")
- };
- //等价的方法
- IEnumerator enuerator = persons.GetEnumerator();
- while (enuerator.MoveNext())
- {
- Person p = enuerator.Current as Person;
- Console.WriteLine(p.firstName + " " + p.lastName);
- }
- Console.Read();
- }
- }
- }
我们知道GetEnumerator()方法返回一个IEnumerator类型的接口,在IEnumerator接口中有一个Current属性来返回当前元素,而其MoveNext()方法又可以移动到集合的下一个元素(有则返回true,无则返回false),如此反复就形成了对整个集合的迭代(具体原理可以参见上面链接的内容)。
二、传统集合的遍历
上面我们谈到Array类实现了IEnumerable接口中的GetEnumerator()方法,因此可以使用foreach来循环遍历,那么我们自己当然也同样可以实现相关接口。
People类
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace IteratorDemo
- {
- 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];
- }
- }
- public IEnumerator GetEnumerator()
- {
- return new PeopleEnum(_people);
- }
- }
- }
PeopleEnum类
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace IteratorDemo
- {
- class PeopleEnum:IEnumerator
- {
- public Person[] _people;
- int position = -1;
- public PeopleEnum(Person[] list)
- {
- _people = list;
- }
- public bool MoveNext()
- {
- position++;
- return (position < _people.Length);
- }
- public void Reset()
- {
- position = -1;
- }
- public object Current
- {
- get
- {
- try
- {
- return _people[position];
- }
- catch (IndexOutOfRangeException)
- {
- throw new InvalidOperationException();
- }
- }
- }
- }
- }
在上面People类就实现了IEnumerable接口(当然截至到目前其相关内容也必须实现IEnumerator类),因此我们就可以遍历People类:
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace IteratorDemo
- {
- class Program
- {
- /*
- * 实现IEnumerable(显然目前我们必须先实现IEnumerator)
- */
- static void Main(string[] args)
- {
- Person[] persons = new Person[] {
- new Person("Kenshin","Cui"),
- new Person("Miaoer","Sun"),
- new Person("Jinjuan","Shen"),
- new Person("Yanxin","Nie")
- };
- People pe = new People(persons);
- foreach (Person p in pe)
- {
- Console.WriteLine(p.firstName + " " + p.lastName);
- }
- Console.Read();
- }
- }
- }
三、使用迭代器
截止到现在我们可以看到如果让一个类或结构支持foreach就必须实现整个IEnumerable接口,这显然过于麻烦,毕竟我们不想在这方面花费太多的时间,那么此时我们就来使用迭代器吧。创建迭代器的最常用的方法就是对IEnumerable接口实现GetEnumerator()方法,例如将上面的People类可以写成这样:
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace IteratorDemo
- {
- 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];
- }
- }
- public IEnumerator GetEnumerator()
- {
- for (int i = 0; i < _people.Length; ++i)
- {
- yield return _people[i];
- }
- }
- }
- }
从上面我们可以看到我们完全省略了创建PeopleEnum的过程(事实上我们还可以更简单,下面我们就可以看到,这里主要为了和上面的例子做个对比),当然这一切都归功于迭代器的功劳。迭代器使用yield return语句返回每个元素,yield break终止迭代(其返回类型必须为IEnumerable/IEnumerable、IEnumerator/Ienumerator类型)。yield关键字用于指定返回值,到达yield break时会保存当前位置,直到下次调用迭代器时将从此位置从新开始执行。当编译器见到迭代器时,会自动生成IEnumerable/IEnumerable接口的Current、MoveNext和Dispose方法。
当然可能有朋友到现在还有些模糊,那么您不妨简单的理解为:迭代器就是使用yield帮助我们省去了实现IEnumerator的麻烦(虽然,事实上远不止那么简单)。
之所以今天会想起这个话题,其实是因为偶然看到一段类似下面代码:
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace IteratorDemo
- {
- class Program
- {
- private static IList<Person> FilterPeople(IEnumerable<Person> people)
- {
- IList<Person> persons = new List<Person>();
- foreach (Person p in people)
- {
- if (p.lastName == "Cui")
- {
- persons.Add(p);
- }
- }
- return persons;
- }
- static void Main(string[] args)
- {
- Person[] persons = new Person[] {
- new Person("Kenshin","Cui"),
- new Person("Miaoer","Sun"),
- new Person("Jinjuan","Shen"),
- new Person("Yanxin","Nie")
- };
- foreach(Person p in FilterPeople(persons))
- {
- Console.WriteLine(p.firstName + " " + p.lastName);
- }
- Console.Read();
- }
- }
- }
想象一下如果使用迭代块(包含yield语句的方法或属性)会不会更优雅呢:
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace IteratorDemo
- {
- class Program
- {
- /*
- * 使用迭代快简化类似的方法
- */
- private static IEnumerable<Person> FilterPeople(IEnumerable<Person> people)
- {
- foreach(Person p in people)
- {
- if(p.lastName=="Cui")
- {
- yield return p;
- }
- }
- }
- static void Main(string[] args)
- {
- Person[] persons = new Person[] {
- new Person("Kenshin","Cui"),
- new Person("Miaoer","Sun"),
- new Person("Jinjuan","Shen"),
- new Person("Yanxin","Nie")
- };
- foreach(Person p in FilterPeople(persons))
- {
- Console.WriteLine(p.firstName + " " + p.lastName);
- }
- Console.Read();
- }
- }
- }