一.迭代器介绍
迭代器记录了集合的某个位置,它使得程序只能向前移动,C#中使用foreach语句来实现访问迭代器的内置支持;foreach被编译后,会调用GetEnumerator来返回一个迭代器,也就是集合的初始位置。
二.自定义迭代器的实现
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Enumerator { public class Friend { private string name; public string Name { get { return name; } set { name = value; } } public Friend(string name) { this.name = name; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Enumerator { public class Friends:IEnumerable { private Friend[] friendArray; public Friends() { friendArray = new Friend[] { new Friend("张三"), new Friend("李四"), new Friend("王五") }; } //迭代器的实现 public IEnumerator GetEnumerator() { for(int index = 0; index < friendArray.Length; index++) { yield return friendArray[index]; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Enumerator { class Program { static void Main(string[] args) { Friends friendCollection = new Friends(); foreach(Friend f in friendCollection) { Console.WriteLine(f.Name); } Console.ReadKey(); } } }
上述代码中只用了关键字yield return就完成了迭代器的实现,它的作用是在告诉编译器,GetEnumerator方法不是一个普通方法,而是实现迭代器的方法,当编译器看到yield return语句时,会在中间代码中为我们生成一个IEnumerator接口对象。
三.迭代器的执行过程