我正在使用产量并在某处罢工,任何人都可以解释我的场景如何产量工作如下所示。
public static IEnumerable Power(int number, int exponent)
{
int result = 1;
int counter = 0;
Console.WriteLine("Inside Power - Before While");
while (counter++ < exponent)
{
Console.WriteLine("Inside Power - Inside While");
result = result * number;
yield return result;
//Console.WriteLine("New line added");
}
Console.WriteLine("Inside Power - After While");
}
static void Main(string[] args)
{
foreach (int i in Power(2, 8))
{
Console.WriteLine("{0}", i);
}
}
所以我们在这里得到的输出是
Inside Power - Before While
Inside power - Inside While
2
Inside power - Inside While
4
Inside power - Inside While
8
Inside power - Inside While
16
Inside power - Inside While
32
Inside power - Inside While
64
Inside power - Inside While
128
Inside power - Inside While
256
Inside power - AfterWhile
所以我的问题是指针如何从 foreach 转移到 Enumerable 方法 while 循环和打印等等。为什么不调用整个方法,并且每次只执行while循环。