• C#2.0中使用yield关键字简化枚举器的实现


    我们知道要使用foreach语句从客户端代码中调用迭代器,必需实现IEnumerable接口来公开枚举器,IEnumerable是用来公开枚举器的,它并不实现枚举器,要实现枚举器必需实现IEnumerator接口。现在用 yield关键字,您不必实现整个 IEnumerator 接口。从而简化了代码. 而且可以实现更加灵活的枚举。

    如下代码:
     1// Declare the collection:
     2public class SampleCollection
     3{
     4    public int[] items;
     5
     6    public SampleCollection()
     7    {
     8        items = new int[5] { 5, 4, 7, 9, 3 };
     9    }
    10
    11    public System.Collections.IEnumerable BuildCollection()
    12    {
    13        for (int i = 0; i < items.Length; i++)
    14        {
    15            yield return items[i];
    16        }
    17    }
    18}
    19
    20class MainClass
    21{
    22    static void Main()
    23    {
    24        SampleCollection col = new SampleCollection();
    25
    26        // Display the collection items:
    27        System.Console.WriteLine("Values in the collection are:");
    28        foreach (int i in col.BuildCollection())
    29        {
    30            System.Console.Write(i + " ");
    31        }
    32    }
    33}
    34
    或者

    Code
     1class Program
     2    {
     3        static void Main(string[] args)
     4        {
     5            SampleCollection s = new SampleCollection();
     6           
     7            foreach(int i in s)
     8            {
     9                Console.WriteLine(i.ToString());
    10            }
    11        }
    12    }
    13
    14    public class SampleCollection:IEnumerable
    15    {
    16        public int[] items;
    17
    18        public SampleCollection()
    19        {
    20            items = new int[5] { 5, 4, 7, 9, 3 };
    21        }
    22
    23        public IEnumerator GetEnumerator()
    24        {
    25            for (int i = 0; i < items.Length; i++)
    26            {
    27                yield return items[i];
    28            }
    29        }
    30    }
    我们在注意的是C#2.0增加了yield关键字,简化了对枚举器的实现。但他只不过是在编译器上的改变,实际上是由编译器帮我们实现了IEnumerator接口的枚举器.

  • 相关阅读:
    jvm中的热点代码检测机制
    oracle复制表结构和表数据
    sqlserver复制表结构和表数据
    mysql创建和删除唯一索引(unique key)
    sqlserver中的concat()函数
    Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.
    使用AopContxt.currentProxy()方法获取当前代理对象
    poi锁定单元格
    poi设置文本类型
    javascript中的this理解
  • 原文地址:https://www.cnblogs.com/wwwzzg168/p/3569070.html
Copyright © 2020-2023  润新知