知識點 – C#2.0新特性之迭代器, Yield Return

來源:互聯網
上載者:User

引子:http://www.cnblogs.com/yank/archive/2011/07/02/2096240.html

Yield介紹

yield關鍵字向編譯器指示它所在的方法是迭代器塊。

在迭代器塊中,yield 關鍵字與 return 關鍵字結合使用,向列舉程式對象提供一個傳回值,例如,在 foreach 語句的每一次迴圈中返回的值。yield 關鍵字也可與 break 結合使用,表示迭代結束。

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

2.yield break;

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

Yield使用約束

 

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

  • 不允許不安全塊。

  • 方法、運算子或訪問器的參數不能是 ref 或 out。

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

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

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

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

Yield使用樣本

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;
      yieldreturn result;
    }
  }
  staticvoid 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
*/

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.