C# yeild使用

  C# yeild的两种形式的yield语句:

yield return <expression>;
yield break;

  使用 yield return 语句每一次返回每个元素。
  将使用 foreach 语句从客户端代码中调用迭代器。 foreach 循环的每次迭代都会调用迭代器方法。 迭代器方法运行到 yield return 语句时,会返回一个expression表达式并保留当前在代码中的位置。 当下次调用迭代器函数时执行从该位置重新启动。
  可以用 yield break语句来终止迭代。

  示例:

using System;
using System.Collections.Generic;
using System.Text;

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

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

  运行输出:

2
4
8
16
32
64
128
256
请按任意键继续. . .
原文地址:https://www.cnblogs.com/libingql/p/3762327.html