C# yield關鍵字的使用

來源:互聯網
上載者:User
yield(C# 參考)

在迭代器塊中用於向枚舉數對象提供值或發出迭代結束訊號。它的形式為下列之一:

複製代碼

yield return <expression>;yield break;

 備忘

計算運算式並以枚舉數對象值的形式返回;expression 必須可以隱式轉換為迭代器的 yield 類型。

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

  • 不允許不安全塊。

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

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

當和 expression 一起使用時,yield return 語句不能出現在 catch 塊中或含有一個或多個 catch 子句的 try 塊中。有關更多資訊,請參見異常處理語句(C# 參考)。

 樣本

在下面的樣本中,迭代器塊(這裡是方法 Power(int number, int power))中使用了 yield 語句。當調用 Power 方法時,它返回一個包含數字冪的可枚舉對象。注意 Power 方法的傳回型別是 IEnumerable(一種迭代器介面類型)。

複製代碼

// 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);        }    }}

輸出
2 4 8 16 32 64 128 256 
 
原文地址:http://msdn.microsoft.com/zh-cn/library/9k7k7cf0(VS.80).aspx#Mtps_DropDownFilterText

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.