C# 中的yield使用
生活随笔
收集整理的這篇文章主要介紹了
C# 中的yield使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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] {1, 1, 2, 3, 4, 5, 6, 7, 87, 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;
????????}
????}
}
??? 這樣,則只會返回前8個數據.
總結
以上是生活随笔為你收集整理的C# 中的yield使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 手机游戏怎么到电脑玩(手机上的游戏怎么在
- 下一篇: 卿本佳人奈何做贼可以形容什么(卿本佳人