yield break;在 yield return 语句中,将计算 expression 并将结果以值的形式返回给枚举器对象;expression 必须可以隐式转换为 yield 类型的迭代器。在 yield break 语句中,控制权将无条件地返回给迭代器的调用方,该调用方为枚举器对象的 IEnumerator.MoveNext 方法
(或其对应的泛型 System.Collections.Generic.IEnumerable<T>)或 Dispose 方法。
-
不允许不安全块。
-
方法、运算符或访问器的参数不能是 ref 或 out。
-
yield return 语句不能放在 try-catch 块中的任何位置。 该语句可放在后跟 finally 块的 try 块中。
-
yield break 语句可放在 try 块或 catch 块中,但不能放在 finally 块中。
2 {
3 // Create an array of integers.
4 public static int[] ints = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377 };
5
6 // Define a property that returns only the even numbers.
7 public static IEnumerable<int> GetEven()
8 {
9 // Use yield to return the even numbers in the list.
10 foreach (int i in ints)
11 if (i % 2 == 0)
12 yield return i;
13 }
14
15 static void Main(string[] args)
16 {
17
18 // Display the even numbers.
19 Console.WriteLine("Even numbers");
20 foreach (int i in NumberList.GetEven())
21 Console.WriteLine(i);
22 }
23
24 }