c# 語法糖 yield


  • 怎么使用

 

首次看到這個語法在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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM