在迭代器塊中用於向枚舉數對象提供值或發出迭代結束訊號。它的形式為下列之一:
| |
|
yield return <expression>;yield break; |
{
ExpandCollapse(languageReferenceRemarksToggle)
}" onkeypress="function onkeypress()
{
ExpandCollapse_CheckKey(languageReferenceRemarksToggle, event)
}">備忘
計算運算式並以枚舉數對象值的形式返回;expression 必須可以隱式轉換為迭代器的 yield 類型。
yield 語句只能出現在 iterator 塊中,該塊可用作方法、運算子或訪問器的體。這類方法、運算子或訪問器的體受以下約束的控制:
yield 語句不能出現在匿名方法中。有關更多資訊,請參見匿名方法(C# 編程指南)。
當和 expression 一起使用時,yield return 語句不能出現在 catch 塊中或含有一個或多個 catch 子句的 try 塊中。有關更多資訊,請參見異常處理語句(C# 參考)。
{
ExpandCollapse(exampleToggle)
}" onkeypress="function onkeypress()
{
ExpandCollapse_CheckKey(exampleToggle, event)
}">樣本
在下面的樣本中,迭代器塊(這裡是方法 Power(int number, int power))中使用了 yield 語句。當調用 Power 方法時,它返回一個包含數字冪的可枚舉對象。注意 Power 方法的傳回型別是 IEnumerable(一種迭代器介面類型)。
| |
{ CopyCode(this) }" onmouseover="function onmouseover() { ChangeCopyCodeIcon(this) }" onmouseout="function onmouseout() { ChangeCopyCodeIcon(this) }" onkeypress="function onkeypress() { CopyCode_CheckKey(this, event) }">複製代碼 |
// yield-example.csusing System;using System.Collections;public class List{ public static IEnumerable Power(int number, int exponent) { int counter = 0; int result = 1; while (counter++ < exponent) { result = result * number; yield return result; } } static void Main() { // Display powers of 2 up to the exponent 8: foreach (int i in Power(2, 8)) { Console.Write("{0} ", i); } }} |