C#中yield用法


注:本文為個人學習摘錄,原文地址:http://www.cnblogs.com/yank/archive/2011/07/02/2096240.html

 

yield 關鍵字向編譯器指示它所在的方法是迭代器塊。編譯器生成一個類來實現迭代器塊中表示的行為。在迭代器塊中,yield 關鍵字與 return 關鍵字結合使用,向枚舉器對象提供值。這是一個返回值,例如,在 foreach 語句的每一次循環中返回的值。yield 關鍵字也可與 break 結合使用,表示迭代結束。

例子:
yield return <expression>;
yield break;

在 yield return 語句中,將計算 expression 並將結果以值的形式返回給枚舉器對象;expression 必須可以隱式轉換為 yield 類型的迭代器。

yield break 語句中,控制權將無條件地返回給迭代器的調用方,該調用方為枚舉器對象的 IEnumerator.MoveNext 方法(或其對應的泛型 System.Collections.Generic.IEnumerable<T>)或 Dispose 方法。

yield 語句只能出現在 iterator 塊中,這種塊可作為方法、運算符或訪問器的主體實現。這類方法、運算符或訪問器的體受以下約束的控制:

  • 不允許不安全塊。

  • 方法、運算符或訪問器的參數不能是 refout

  • yield return 語句不能放在 try-catch 塊中的任何位置。該語句可放在后跟 finally 塊的 try 塊中。

  • yield break 語句可放在 try 塊或 catch 塊中,但不能放在 finally 塊中。

yield 語句不能出現在匿名方法中。有關更多信息,請參見匿名方法(C# 編程指南)

當和 expression 一起使用時,yield return 語句不能出現在 catch 塊中或含有一個或多個 catch 子句的 try 塊中。

復制代碼
public class List
{
// 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
*/
復制代碼

 


免責聲明!

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



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