c# yield用法

注意事项:
1、yield语句只能出现在迭代块中;
2、
yield return 语句不能放在 try-catch 块中的任何位置。 该语句可放在后跟 finally 块的 try 块中
3、
yield break 语句可放在 try 块或 catch 块中,但不能放在 finally 块中。
4、不允许不安全块
5、不能放在匿名函数中

示例:

public
class List { //using System.Collections; 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); } } } /* Output: 2 4 8 16 32 64 128 256 */ 来自msdn:http://msdn.microsoft.com/zh-cn/library/9k7k7cf0(v=vs.100).aspx

你可能感兴趣的:(yield)