zoukankan      html  css  js  c++  java
  • 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接口的枚举器.

  • 相关阅读:
    期货结算 期货算法公式
    c# websocket 服务端,客户端 兼容低版本IE,支持超长数据传输 附源码
    翻译API translate api 翻译文档api 百度翻译
    asp.net c# 网页 导出excel 多表格 多个sheet
    创建单线程单元 asp.net下使用WebBrowser
    c++ 修改内存
    c++ int to byte
    webservice 第一节 .net SoapHeader验证
    myeclipse maven编译出错
    java用正则表达式获取domain
  • 原文地址:https://www.cnblogs.com/wwwzzg168/p/3569070.html
Copyright © 2011-2022 走看看