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接口的枚举器.

  • 相关阅读:
    使用EF进行简单的增删改查
    观察者模式(委托事件的小应用)
    lambda表达式和表达式树
    socket知识总结
    xml读写Demo
    winfrom DataGridView Demo
    6月26号.NET面试题(程序题部分)只要做懂这3道题肯定能脱离菜鸟称号!
    多线程与异步编程知识简单总结
    15年6月14号面试中没有回答出来的问题
    2020.5.15记一次阿里电话面试经历
  • 原文地址:https://www.cnblogs.com/wwwzzg168/p/3569070.html
Copyright © 2011-2022 走看看