在迭代器塊中用于向枚舉數對象提供值或發出迭代結束信號。它的形式為下列之一:
yield return <expression>;
yield break;
備注:
計算表達式并以枚舉數對象值的形式返回;expression 必須可以隱式轉換為迭代器的 yield 類型。
yield 語句只能出現在 iterator 塊中,該塊可用作方法、運算符或訪問器的體。這類方法、運算符或訪問器的體受以下約束的控制:不允許不安全塊。
方法、運算符或訪問器的參數不能是 ref 或 out。
yield 語句不能出現在匿名方法中。
當和 expression 一起使用時,yield return 語句不能出現在 catch 塊中或含有一個或多個 catch 子句的 try 塊中。
yield return 提供了迭代器一個比較重要的功能,即取到一個數據后馬上返回該數據,不需要全部數據裝入數列完畢,這樣有效提高了遍歷效率。
以下是一個比較特殊的例子:
C# 中yield 的用法代碼引用:
using System;using System.Collections;using System.IO;using Microsoft.Office.Interop.PowerPoint;using Microsoft.Office.Core;using System.Windows.Forms;using System.Threading;namespace test{ public class Persons : System.Collections.IEnumerable { #region IEnumerable 成員 public System.Collections.IEnumerator GetEnumerator() { yield return "1"; Thread.Sleep(5000); yield return "2"; Thread.Sleep(5000); yield return "3"; Thread.Sleep(5000); yield return "4"; Thread.Sleep(5000); yield return "5"; Thread.Sleep(5000); yield return "6"; } #endregion } class program { static void Main() { Persons arrPersons = new Persons(); foreach (string s in arrPersons) { System.Console.WriteLine(s); } System.Console.ReadLine(); } } }
每隔5秒鐘, 控制臺就會輸出一個數據,直到全部數據輸入完畢。
以上就是關于C#中yield用法使用說明,希望對大家的學習有所幫助。
新聞熱點
疑難解答