直接出栗子:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 foreach (var item in FilterWithoutYield) 6 { 7 Console.WriteLine(item); 8 } 9 Console.ReadKey(); 10 } 11 12 13 //申明属性,定义数据来源 14 public static List<int> Data 15 { 16 get 17 { 18 return new List<int>(){1,2,3,4,5,6,7,8}; 19 } 20 } 21 22 //申明属性,过滤器(不适用yield) 23 public static IEnumerable<int> FilterWithoutYield 24 { 25 get 26 { 27 var result = new List<int>(); 28 foreach (var i in Data) 29 { 30 if (i > 4) 31 result.Add(i); 32 } 33 return result; 34 } 35 } 36 }
加上yeild之后,
1 //申明属性,过滤器(使用yield) 2 public static IEnumerable<int> FilterWithoutYield 3 { 4 get 5 { 6 foreach (var i in Data) 7 { 8 if (i > 4) 9 yield return i; 10 } 11 } 12 }
使用yeild要注意一下几点:
-
yield return 语句不能放在 try-catch 块中的任何位置。 该语句可放在后跟 finally 块的 try 块中。
- yield break 语句可放在 try 块或 catch 块中,但不能放在 finally 块中。
- yield 语句不能出现在匿名方法中
- 迭代器方法的参数中不能有ref和out
解释一下迭代器: 是一种方法, get访问器, 或者运算符, 通过使用yield关键字对属组或者集合执行自定义迭代, yield返回的语句会导致原序列中的元素在访问原序列中的下一个元素之前立即返回给调用方.
1 public class List 2 { 3 //using System.Collections; 4 public static IEnumerable Power(int number, int exponent) 5 { 6 int counter = 0; 7 int result = 1; 8 while (counter++ < exponent) 9 { 10 result = result * number; 11 yield return result; 12 } 13 } 14 15 static void Main() 16 { 17 // Display powers of 2 up to the exponent 8: 18 foreach (int i in Power(2, 8)) 19 { 20 Console.Write("{0} ", i); 21 } 22 } 23 } 24 /* 25 Output: 26 2 4 8 16 32 64 128 256 27 */