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

来源:学生作业帮助网 编辑:作业帮 时间:2024/04/28 12:39:39
C#中的yield return 和return有什么区别呀.

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