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

    迭代器:就是对可枚举类型的简化,实现的功能与可枚举类型是一样的,可以使foreach遍历类...只是由.net内部帮我们创建枚举数,无须手动创建.

    使用迭代器的关键字:yield return--延迟注册

    延迟注册也就是当编译器执行到带有yield return方法时,暂不执行该方法,等到在foreach中去执行--详情参考http://www.cnblogs.com/artech/archive/2010/10/28/yield.html

     1  class Program
    2 {
    3 static void Main(string[] args)
    4 {
    5 IEnumerable<Chinese> cs = GetChinese();
    6
    7 foreach (Chinese c in cs)
    8 {
    9 c.Age = 1;
    10 Console.WriteLine(c.Age);
    11 }
    12
    13 foreach (Chinese c in cs)
    14 {
    15 Console.WriteLine(c.Age);
    16 }
    17
    18 Console.ReadKey();
    19 }
    20
    21 static IEnumerable<Chinese> GetChinese()
    22 {
    23 yield return new Chinese("tom", 11);
    24 yield return new Chinese("jeery", 15);
    25 yield return new Chinese("marry", 22);
    26 }
    27 }
    28


    这就简单的迭代器的运用...

    现在让我们重写下之前用可枚举类型和枚举数写的代码:

     1 class Program
    2 {
    3 static void Main(string[] args)
    4 {
    5 string[] data = { "sky", "ok", "mother", "father", "good", "wonderful" };
    6 Person p = new Person("tom", 18);
    7 p.See(data);
    8 p.See("wather");
    9
    10 foreach (string item in p)
    11 {
    12 Console.WriteLine(item);
    13 }
    14
    15 Console.ReadKey();
    16 }
    17 }
    18
    19 //那么现在假设Person类有一个记忆功能,现在我想用foreach遍历person类读取,记忆中的数据,并把数据显示出来..
    20 //所以我先声明一个Person类,他有Name,Age,Memory字段,还有一个构造函数以及一个See方法,模拟人从外界得到记忆...
    21 class Person
    22 {
    23 public int Age;
    24 public string Name;
    25 List<string> memory = new List<string>();
    26
    27 //外界只能读取记忆,不能设置记忆
    28 public string[] Memory
    29 {
    30 get
    31 {
    32 return memory.ToArray();
    33 }
    34 }
    35
    36 public Person(string name, int age)
    37 {
    38 this.Age = age;
    39 this.Name = name;
    40 }
    41
    42 public void See(string data)
    43 {
    44 memory.Add(data);
    45 }
    46
    47 public void See(string[] data)
    48 {
    49 memory.AddRange(data);
    50 }
    51
    52 //思考下为什么这里返回值不是IEnumerable?而是IEnumerator..
    53 public IEnumerator<string> GetEnumerator()//迭代器
    54 {
    55 foreach (string s in memory)
    56 {
    57 yield return s;
    58 }
    59 }
    60 }

      运行后代码如下     

    sky
    ok
    mother
    father
    good
    wonderful
    wather

    思考下为什么这里返回值不是IEnumerable?而是IEnumerator..
    如果IEnumerable的话,这里就不能直接foreach (string item inp),而应该是foreach (string item inp.GetEnumerator()),为什么?在可枚举类型中,要使一个类可枚举,就必须使类实现IEnumerable接口,而该接口中有且只有一个方法GetEnumerator,而迭代器仅仅只是对对可枚举类型的简化,所以如果类中有GetEnumerator方法,.net会默认调用,当然前提是该方法的返回值要跟IEnumerable的接口方法的返回值一样...
  • 相关阅读:
    C#如何调用非托管的C++Dll
    CList 点击表头排序 (3)两种排序的第二种
    CList 点击表头排序 (2)两种排序方法中其中一种
    CList 点击表头排序 (1)SortItems函数
    CListCtrl 隔行变色
    C++去掉字符串中首尾空格和所有空格
    Dialog和FormView如何派生通用类
    STL中erase()的陷阱
    socket 笔记(一)
    prettyJson V7.1 使用
  • 原文地址:https://www.cnblogs.com/shysky77/p/2278578.html
Copyright © 2011-2022 走看看