C#中yield用法使用说明
在迭代器块中用于向枚举数对象提供值或发出迭代结束信号。它的形式为下列之一:
yieldreturn<expression>;
yieldbreak;
备注:
计算表达式并以枚举数对象值的形式返回;expression必须可以隐式转换为迭代器的yield类型。
yield语句只能出现在iterator块中,该块可用作方法、运算符或访问器的体。这类方法、运算符或访问器的体受以下约束的控制:不允许不安全块。
方法、运算符或访问器的参数不能是ref或out。
yield语句不能出现在匿名方法中。
当和expression一起使用时,yieldreturn语句不能出现在catch块中或含有一个或多个catch子句的try块中。
yieldreturn提供了迭代器一个比较重要的功能,即取到一个数据后马上返回该数据,不需要全部数据装入数列完毕,这样有效提高了遍历效率。
以下是一个比较特殊的例子:
C#中yield的用法代码引用:
usingSystem; usingSystem.Collections; usingSystem.IO; usingMicrosoft.Office.Interop.PowerPoint; usingMicrosoft.Office.Core; usingSystem.Windows.Forms; usingSystem.Threading; namespacetest { publicclassPersons:System.Collections.IEnumerable { #regionIEnumerable成员 publicSystem.Collections.IEnumeratorGetEnumerator() { yieldreturn"1"; Thread.Sleep(5000); yieldreturn"2"; Thread.Sleep(5000); yieldreturn"3"; Thread.Sleep(5000); yieldreturn"4"; Thread.Sleep(5000); yieldreturn"5"; Thread.Sleep(5000); yieldreturn"6"; } #endregion } classprogram { staticvoidMain() { PersonsarrPersons=newPersons(); foreach(stringsinarrPersons) { System.Console.WriteLine(s); } System.Console.ReadLine(); } } }
每隔5秒钟,控制台就会输出一个数据,直到全部数据输入完毕。
以上就是关于C#中yield用法使用说明,希望对大家的学习有所帮助。