示例代码:

神奇的地方在于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);
        }
    }
}

 

 

 

 

相关文章:

  • 2022-12-23
  • 2023-03-12
  • 2021-10-19
  • 2021-06-25
  • 2022-02-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-04
  • 2021-08-27
  • 2022-01-15
  • 2022-01-24
  • 2021-11-03
  • 2021-10-15
  • 2021-12-10
相关资源
相似解决方案