zoukankan      html  css  js  c++  java
  • C#迭代器

    摘要:迭代器是C#2.0中添加的功能,它能够使我们在类或结构中支持foreach迭代,而不必实现整个IEnumerable/IEnumerable接口。今天我们就一块看一下什么是c#中的迭代器吧。

    主要内容:
    1.foreach的运行机制
    2.传统集合的遍历
    3.使用迭代器

    一、foreach的运行机制

    我们在程序中经常会用到foreach,如果你把它理解成是for的一种简写形式的话那就太大材小用了,事实上foreach中包含了丰富的内容。我们知道要使用foreach遍历集合就必须实现IEnumerable接口,而要实现IEnumerable接口就要实现IEnumerator接口。关于如何实现这两个接口我们在第二部分会看到,在谈foreach的运行机制之前请允许我使用msdn中的Person类(我们下面的几部分中我们还会用到相关的People和PeopleEnum类):
    View Code
    1 using System;
    2 using System.Collections.Generic;
    3 using System.Linq;
    4 using System.Text;
    5
    6 namespace IteratorDemo
    7 {
    8 class Person
    9 {
    10 public Person(string fName, string lName)
    11 {
    12 this.firstName = fName;
    13 this.lastName = lName;
    14 }
    15
    16 publicstring firstName;
    17 publicstring lastName;
    18 }
    19 }
    当然具体细节我就不再说了,有了上面的Person类我们就可以运行下面的代码了:
    View Code
    1 using System;
    2 using System.Collections;
    3 using System.Collections.Generic;
    4 using System.Linq;
    5 using System.Text;
    6
    7 namespace IteratorDemo
    8 {
    9 class Program
    10 {
    11 staticvoid Main(string[] args)
    12 {
    13 Person[] persons =new Person[] {
    14 new Person("Kenshin","Cui"),
    15 new Person("Miaoer","Sun"),
    16 new Person("Jinjuan","Shen"),
    17 new Person("Yanxin","Nie")
    18 };
    19 foreach (Person p in persons)
    20 {
    21 Console.WriteLine(p.firstName +""+ p.lastName);
    22 }
    23 Console.Read();
    24 }
    25
    26 }
    27 }
    具体的运行结果也没有什么可说的,可是为什么会有这样的结果呢?原因可以分两层来解释:第一就是我们的Persons是使用[]符号声明,这是一个Array类的记号。而Array类实现了IEnumerable接口中GetEnumerator()方法,因此它可以使用foreach进行迭代;第二,之所以实现IEnumerable接口的GetEnumerator()方法就能够迭代是因为foreach将上面的代码解析成如下的形式:
    View Code
    1 using System;
    2 using System.Collections;
    3 using System.Collections.Generic;
    4 using System.Linq;
    5 using System.Text;
    6
    7 namespace IteratorDemo
    8 {
    9 class Program
    10 {
    11 staticvoid Main(string[] args)
    12 {
    13 Person[] persons =new Person[] {
    14 new Person("Kenshin","Cui"),
    15 new Person("Miaoer","Sun"),
    16 new Person("Jinjuan","Shen"),
    17 new Person("Yanxin","Nie")
    18 };
    19
    20 //等价的方法
    21 IEnumerator enuerator = persons.GetEnumerator();
    22 while (enuerator.MoveNext())
    23 {
    24 Person p = enuerator.Current as Person;
    25 Console.WriteLine(p.firstName +""+ p.lastName);
    26 }
    27 Console.Read();
    28 }
    29
    30 }
    31 }
    我们知道GetEnumerator()方法返回一个IEnumerator类型的接口,在IEnumerator接口中有一个Current属性来返回当前元素,而其MoveNext()方法又可以移动到集合的下一个元素(有则返回true,无则返回false),如此反复就形成了对整个集合的迭代(具体原理可以参见上面链接的内容)。

    二、传统集合的遍历

    上面我们谈到Array类实现了IEnumerable接口中的GetEnumerator()方法,因此可以使用foreach来循环遍历,那么我们自己当然也同样可以实现相关接口。
    People类
    View Code
    1 using System;
    2 using System.Collections;
    3 using System.Collections.Generic;
    4 using System.Linq;
    5 using System.Text;
    6
    7 namespace IteratorDemo
    8 {
    9 class People:IEnumerable
    10 {
    11 private Person[] _people;
    12 public People(Person[] pArray)
    13 {
    14 _people =new Person[pArray.Length];
    15
    16 for (int i =0; i < pArray.Length; i++)
    17 {
    18 _people[i] = pArray[i];
    19 }
    20 }
    21
    22 public IEnumerator GetEnumerator()
    23 {
    24 returnnew PeopleEnum(_people);
    25 }
    26 }
    27 }
    PeopleEnum类
    View Code
    1 using System;
    2 using System.Collections;
    3 using System.Collections.Generic;
    4 using System.Linq;
    5 using System.Text;
    6
    7 namespace IteratorDemo
    8 {
    9 class PeopleEnum:IEnumerator
    10 {
    11 public Person[] _people;
    12 int position =-1;
    13
    14 public PeopleEnum(Person[] list)
    15 {
    16 _people = list;
    17 }
    18
    19 publicbool MoveNext()
    20 {
    21 position++;
    22 return (position < _people.Length);
    23 }
    24
    25 publicvoid Reset()
    26 {
    27 position =-1;
    28 }
    29
    30 publicobject Current
    31 {
    32 get
    33 {
    34 try
    35 {
    36 return _people[position];
    37 }
    38 catch (IndexOutOfRangeException)
    39 {
    40 thrownew InvalidOperationException();
    41 }
    42 }
    43 }
    44 }
    45 }
    在上面People类就实现了IEnumerable接口(当然截至到目前其相关内容也必须实现IEnumerator类),因此我们就可以遍历People类:
    View Code
    1 using System;
    2 using System.Collections;
    3 using System.Collections.Generic;
    4 using System.Linq;
    5 using System.Text;
    6
    7 namespace IteratorDemo
    8 {
    9 class Program
    10 {
    11 /*
    12 * 实现IEnumerable(显然目前我们必须先实现IEnumerator)
    13 */
    14 staticvoid Main(string[] args)
    15 {
    16 Person[] persons =new Person[] {
    17 new Person("Kenshin","Cui"),
    18 new Person("Miaoer","Sun"),
    19 new Person("Jinjuan","Shen"),
    20 new Person("Yanxin","Nie")
    21 };
    22 People pe =new People(persons);
    23 foreach (Person p in pe)
    24 {
    25 Console.WriteLine(p.firstName +""+ p.lastName);
    26 }
    27 Console.Read();
    28 }
    29
    30 }
    31 }

    三、使用迭代器

    截止到现在我们可以看到如果让一个类或结构支持foreach就必须实现整个IEnumerable接口,这显然过于麻烦,毕竟我们不想在这方面花费太多的时间,那么此时我们就来使用迭代器吧。创建迭代器的最常用的方法就是对IEnumerable接口实现GetEnumerator()方法,例如将上面的People类可以写成这样:
    View Code
    1 using System;
    2 using System.Collections;
    3 using System.Collections.Generic;
    4 using System.Linq;
    5 using System.Text;
    6
    7 namespace IteratorDemo
    8 {
    9 class People:IEnumerable
    10 {
    11 private Person[] _people;
    12 public People(Person[] pArray)
    13 {
    14 _people =new Person[pArray.Length];
    15
    16 for (int i =0; i < pArray.Length; i++)
    17 {
    18 _people[i] = pArray[i];
    19 }
    20 }
    21
    22 public IEnumerator GetEnumerator()
    23 {
    24 for (int i =0; i < _people.Length; ++i)
    25 {
    26 yieldreturn _people[i];
    27 }
    28 }
    29 }
    30 }
    从上面我们可以看到我们完全省略了创建PeopleEnum的过程(事实上我们还可以更简单,下面我们就可以看到,这里主要为了和上面的例子做个对比),当然这一切都归功于迭代器的功劳。迭代器使用yield return语句返回每个元素,yield break终止迭代(其返回类型必须为IEnumerable/IEnumerable、IEnumerator/Ienumerator类型)。yield关键字用于指定返回值,到达yield break时会保存当前位置,直到下次调用迭代器时将从此位置从新开始执行。当编译器见到迭代器时,会自动生成IEnumerable/IEnumerable接口的Current、MoveNext和Dispose方法。
    当然可能有朋友到现在还有些模糊,那么您不妨简单的理解为:迭代器就是使用yield帮助我们省去了实现IEnumerator的麻烦(虽然,事实上远不止那么简单)。
    之所以今天会想起这个话题,其实是因为偶然看到一段类似下面代码:
    View Code
    1 using System;
    2 using System.Collections;
    3 using System.Collections.Generic;
    4 using System.Linq;
    5 using System.Text;
    6
    7 namespace IteratorDemo
    8 {
    9 class Program
    10 {
    11 privatestatic IList<Person> FilterPeople(IEnumerable<Person> people)
    12 {
    13 IList<Person> persons =new List<Person>();
    14 foreach (Person p in people)
    15 {
    16 if (p.lastName =="Cui")
    17 {
    18 persons.Add(p);
    19 }
    20 }
    21 return persons;
    22 }
    23 staticvoid Main(string[] args)
    24 {
    25 Person[] persons =new Person[] {
    26 new Person("Kenshin","Cui"),
    27 new Person("Miaoer","Sun"),
    28 new Person("Jinjuan","Shen"),
    29 new Person("Yanxin","Nie")
    30 };
    31 foreach(Person p in FilterPeople(persons))
    32 {
    33 Console.WriteLine(p.firstName +""+ p.lastName);
    34 }
    35 Console.Read();
    36 }
    37 }
    38 }
    想象一下如果使用迭代块(包含yield语句的方法或属性)会不会更优雅呢:
    View Code
    1 using System;
    2 using System.Collections;
    3 using System.Collections.Generic;
    4 using System.Linq;
    5 using System.Text;
    6
    7 namespace IteratorDemo
    8 {
    9 class Program
    10 {
    11 /*
    12 * 使用迭代快简化类似的方法
    13 */
    14 privatestatic IEnumerable<Person> FilterPeople(IEnumerable<Person> people)
    15 {
    16 foreach(Person p in people)
    17 {
    18 if(p.lastName=="Cui")
    19 {
    20 yieldreturn p;
    21 }
    22 }
    23 }
    24 staticvoid Main(string[] args)
    25 {
    26 Person[] persons =new Person[] {
    27 new Person("Kenshin","Cui"),
    28 new Person("Miaoer","Sun"),
    29 new Person("Jinjuan","Shen"),
    30 new Person("Yanxin","Nie")
    31 };
    32 foreach(Person p in FilterPeople(persons))
    33 {
    34 Console.WriteLine(p.firstName +""+ p.lastName);
    35 }
    36 Console.Read();
    37 }
    38 }
    39 }
    知识共享许可协议
    作品采用知识共享署名 2.5 中国大陆许可协议进行许可,欢迎转载,演绎或用于商业目的。但转载请注明来自崔江涛(KenshinCui),并包含相关链接。
  • 相关阅读:
    根据浏览器是否出现滚动条,显示返回顶部
    HTML5 屏蔽触屏滚动
    url参数中带有+号,服务器端解码之后没了
    jQuery1.9之后使用on()绑定 动态生成元素的 事件无效
    列表页复选框全选效果
    Python安装sqlite3
    python3.5中,import sqlite3 出现 no module named _sqlite3的解决方法
    使用js设置input标签只读 readonly 属性
    怎么获得当前点击的按钮的id名?
    JS 浮点型数字运算(转)
  • 原文地址:https://www.cnblogs.com/kenshincui/p/2005297.html
Copyright © 2011-2022 走看看