C#中的yield return 和return有什么区别呀.

来源:学生作业帮助网 编辑:作业帮 时间:2024/07/13 06:17:21
C#中的yield return 和return有什么区别呀.
x]OA ޴R[bHMD/.d;ٙBjI 4Q$6Z?3] N;M=y9ϾlNgnvsVȜ1! >WT^wJMe bv:uӷow.?+KJ7yoOl5nUo-k;ބg"rB0 n>0bd]iݷGpUfΫ~C|v<͚輖DշyL:яw֪8J1G=Q/K4=k"9d~}=U,m}bmE :]Kx^ (ьe`"Tem7kb S`Fr0G#Ţ%"p1 %LNf&k2ŕÒNOCZޤmPKWJUJT$˵>6'Yrhb G t#e`d- qK~f(4<SjOB AbZ{T:I9

C#中的yield return 和return有什么区别呀.
C#中的yield return 和return有什么区别呀.

C#中的yield return 和return有什么区别呀.
在下面的示例中,迭代器块(这里是方法 Power(int number,int power))中使用了 yield 语句.当调用 Power 方法时,它返回一个包含数字幂的可枚举对象.注意 Power 方法的返回类型是 IEnumerable(一种迭代器接口类型).
// 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);
}
}
}
2 4 8 16 32 64 128 256