yield 關鍵字向編譯器指示它所在的方法是迭代器塊。編譯器生成一個類來實現迭代器塊中表示的行爲。在迭代器塊中,yield 關鍵字與 return 關鍵字結合使用,向枚舉器對象提供值。這是一個返回值,例如,在 foreach 語句的每一次循環中返回的值。yield 關鍵字也可與 break 結合使用,表示迭代結束。express
例子:
yield return <expression>;
yield break;
編程
在 yield return 語句中,將計算 expression 並將結果以值的形式返回給枚舉器對象;expression 必須能夠隱式轉換爲 yield 類型的迭代器。安全
在 yield break 語句中,控制權將無條件地返回給迭代器的調用方,該調用方爲枚舉器對象的 IEnumerator.MoveNext 方法(或其對應的泛型 System.Collections.Generic.IEnumerable<T>)或 Dispose 方法。函數
yield 語句只能出如今 iterator 塊中,這種塊可做爲方法、運算符或訪問器的主體實現。這類方法、運算符或訪問器的體受如下約束的控制:this
不容許不安全塊。spa
yield return 語句不能放在 try-catch 塊中的任何位置。該語句可放在後跟 finally 塊的 try 塊中。code
yield break 語句可放在 try 塊或 catch 塊中,但不能放在 finally 塊中。對象
yield 語句不能出如今匿名方法中。有關更多信息,請參見匿名方法(C# 編程指南)。blog
當和 expression 一塊兒使用時,yield return 語句不能出如今 catch 塊中或含有一個或多個 catch 子句的 try 塊中。
yield是C#爲了簡化遍歷操做實現的語法糖,咱們知道若是要要某個類型支持遍歷就必需要實現系統接口IEnumerable,這個接口後續實現比較繁瑣要寫一大堆代碼才能支持真正的遍歷功能。舉例說明
using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Text; namespace { class Program { static void Main(string[] args) { HelloCollection helloCollection = new HelloCollection(); foreach (string s in helloCollection) { Console.WriteLine(s); } Console.ReadKey(); } } //public class HelloCollection : IEnumerable //{ // public IEnumerator GetEnumerator() // { // yield return "Hello"; // yield return "World"; // } //} public class HelloCollection : IEnumerable { public IEnumerator GetEnumerator() { Enumerator enumerator = new Enumerator(0); return enumerator; } public class Enumerator : IEnumerator, IDisposable { private int state; private object current; public Enumerator(int state) { this.state = state; } public bool MoveNext() { switch (state) { case 0: current = "Hello"; state = 1; return true; case 1: current = "World"; state = 2; return true; case 2: break; } return false; } public void Reset() { throw new NotSupportedException(); } public object Current { get { return current; } } public void Dispose() { } } } }
上面註釋的部分引用了"yield return」,其功能至關於下面全部代碼!能夠看到若是不適用yield須要些不少代碼來支持遍歷操做。
yield return 表示在迭代中下一個迭代時返回的數據,除此以外還有yield break, 其表示跳出迭代,爲了理解兩者的區別咱們看下面的例子
class A : IEnumerable { private int[] array = new int[10]; public IEnumerator GetEnumerator() { for (int i = 0; i < 10; i++) { yield return array[i]; } } }
若是你只想讓用戶訪問ARRAY的前8個數據,則可作以下修改.這時將會用到yield break,修改函數以下
public IEnumerator GetEnumerator() { for (int i = 0; i < 10; i++) { if (i < 8) { yield return array[i]; } else { yield break; } } }