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須要些不少代碼來支持遍歷操做。this

    yield return 表示在迭代中下一個迭代時返回的數據,除此以外還有yield break, 其表示跳出迭代,爲了理解兩者的區別咱們看下面的例子spa

複製代碼
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,修改函數以下code

複製代碼
public IEnumerator GetEnumerator()
{
    for (int i = 0; i < 10; i++)
    {
        if (i < 8)
        {
            yield return array[i];
        }
        else
        {
            yield break;
        }
    }
}
複製代碼

 

    這樣,則只會返回前8個數據.blog

相關文章
相關標籤/搜索