xiacy

导航

6.2.1 迭代器块和 yield return 简介

利用c#2和 yield return 来迭代示例集合

class Program
{
    static void Main(string[] args)
    {
        object[] values = { "a", "b", "c", "d", "e" };
        IterationSample collection = new IterationSample(values, 1);
        foreach (object x in collection)
        {
            Console.WriteLine(x);
        }
    }
}

class IterationSample : IEnumerable
{
    Object[] values;
    Int32 startingPoint;
    public IterationSample(Object[] values, Int32 startingPoint)
    {
        this.values = values;
        this.startingPoint = startingPoint;
    }
    public IEnumerator GetEnumerator()
    {
        for(int index =0;index<values.Length;index++)
            yield return values[(index+startingPoint)%values.Length];
    }
}

示例

在下面的示例中,迭代器块(这里是方法 Power(int number, int power))中使用了 yield 语句。当调用 Power 方法时,它返回一个包含数字幂的可枚举对象。注意 Power 方法的返回类型是 IEnumerable(一种迭代器接口类型)。

class Program
{
    static void Main(string[] args)
    {
        foreach (int i in Power(2, 8))
            Console.WriteLine(i);
    }

    public static IEnumerable Power(int number, int exponent)
    {
        int counter = 0;
        int result = 1;
        while (counter++ < exponent)
        {
            result = result * number;
            yield return result;
        }
    }
}

 

posted on 2012-05-10 22:30  xiacy  阅读(269)  评论(0编辑  收藏  举报