当前位置:编程学习 > C#/ASP.NET >>

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# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,