C 中的 yield 使用

2022-03-11 17:17:38 字數 1082 閱讀 2973

yield是c#為了簡化遍歷操作實現的語法糖,我們知道如果要要某個型別支援遍歷就必須要實現系統介面ienumerable,這個介面後續實現比較繁瑣要寫一大堆**才能支援真正的遍歷功能。舉例說明

using system;

using system.collections.generic;

using system.collections;

using system.linq;

using system.text;

namespace

console.readkey();}}

//public class hellocollection : ienumerable

//

//}public class hellocollection : ienumerable

public class enumerator : ienumerator, idisposable

public bool movenext()

return false;

}public void reset()

public object current

}public void dispose()}}

}上面注釋的部分引用了"yield return」,其功能相當於下面所有**!可以看到如果不適用yield需要些很多**來支援遍歷操作。

yield return 表示在迭代中下乙個迭代時返回的資料,除此之外還有yield break, 其表示跳出迭代,為了理解二者的區別我們看下面的例子

class a : ienumerable

}}如果你只想讓使用者訪問array的前8個資料,則可做如下修改.這時將會用到yield break,修改函式如下

public ienumerator getenumerator()

else

}}這樣,則只會返回前8個資料.

C 中的 yield 使用

yield是c 為了簡化遍歷操作實現的語法糖,我們知道如果要要某個型別支援遍歷就必須要實現系統介面ienumerable,這個介面後續實現比較繁瑣要寫一大堆 才能支援真正的遍歷功能。舉例說明 using system using system.collections.generic using sy...

C 中yield的使用

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

C 中的 yield 使用

yield是c 為了簡化遍歷操作實現的語法糖,我們知道如果要要某個型別支援遍歷就必須要實現系統介面ienumerable,這個介面後續實現比較繁瑣要寫一大堆 才能支援真正的遍歷功能。舉例說明 using system using system.collections.generic using sy...