- 怎么使用
首次看到这个语法在github上,了解记录下yield语法有两种形式:
yield return 表达式
yield break 打断循环,返回到调用方
直接上代码:
1 public static IEnumerable<int> TestEven()
2 { 3 var lst = new List<int>() { 1, 2, 3, 4, 5, 6, 9, 10 }; 4 //try 5 //{ 6 foreach (var item in lst) 7 { 8 if (item > 9) 9 yield break; 10 if (item % 2 == 0) 11 yield return item; 12 } 13 //} 14 //catch (Exception ex) 15 //{ 16 // throw ex; 17 //} 18 19 } 20 static void Main(string[] args) 21 { 22 foreach (var item in TestEven()) 23 { 24 Console.WriteLine(item); 25 } 26 Console.ReadKey();
}
- 注意什么
1. yield return 不能放在try-catch 块中的任何块中,但是可以放在try-finally块的try块中
2. yield break 可以放在try块,catch块但是不能放在finally块中
3.迭代器的参数不能使用ref,in或out