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];

    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個數據.


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM