yield 举例

示例代码:

神奇的地方在于yield返回的是一个IEumerable,可以直接枚举。

// yield-example.cs
using System;
using System.Collections;
public class List
{
    public static IEnumerable Power(int number, int exponent)
    {
        int counter = 0;
        int result = 1;
        while (counter++ < exponent)
        {
            result = result * number;
            yield return result;
        }
    }

    static void Main()
    {
        // Display powers of 2 up to the exponent 8:
        foreach (int i in Power(2, 8))
        {
            Console.Write("{0} ", i);
        }
    }
}

 

 

 

 

posted @ 2013-08-05 10:36  xiaokang088  阅读(176)  评论(0编辑  收藏  举报