注:本文為個人學習摘錄,原文地址:http://www.cnblogs.com/yank/archive/2011/07/02/2096240.html
yield 關鍵字向編譯器指示它所在的方法是迭代器塊。編譯器生成一個類來實現迭代器塊中表示的行為。在迭代器塊中,yield 關鍵字與 return 關鍵字結合使用,向枚舉器對象提供值。這是一個返回值,例如,在 foreach 語句的每一次循環中返回的值。yield 關鍵字也可與 break 結合使用,表示迭代結束。
例子:
yield return <expression>;
yield break;
在 yield break 語句中,控制權將無條件地返回給迭代器的調用方,該調用方為枚舉器對象的 IEnumerator.MoveNext 方法(或其對應的泛型 System.Collections.Generic.IEnumerable<T>)或 Dispose 方法。
yield 語句只能出現在 iterator 塊中,這種塊可作為方法、運算符或訪問器的主體實現。這類方法、運算符或訪問器的體受以下約束的控制:
-
不允許不安全塊。
-
yield return 語句不能放在 try-catch 塊中的任何位置。該語句可放在后跟 finally 塊的 try 塊中。
-
yield break 語句可放在 try 塊或 catch 塊中,但不能放在 finally 塊中。
yield 語句不能出現在匿名方法中。有關更多信息,請參見匿名方法(C# 編程指南)。
當和 expression 一起使用時,yield return 語句不能出現在 catch 塊中或含有一個或多個 catch 子句的 try 塊中。

{
// using System.Collections;
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);
}
}
}
/*
Output:
2 4 8 16 32 64 128 256
*/