C#拾遺系列(6):迭代器

來源:互聯網
上載者:User

1. 樣本:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;

 

namespace NetTest

{

  public  class TestIteration

    {

 

        public void Test()

        {

            SevenColor colorIteration = new SevenColor();

            foreach (string p in colorIteration)

            {

                Console.Out.WriteLine(p);

            }

            Console.Out.WriteLine("-------------Desc-------------------");

            foreach (string c in colorIteration.DescColorIteration(1, 5))

            {

                Console.Out.WriteLine(c);

            }

            Console.Out.WriteLine("--------------multi yield---------");

            foreach (string c in colorIteration.GetMutipleYied())

            {

                Console.Out.WriteLine(c);

            }

        }

    }

 

    public class SevenColor : IEnumerable

    {

        string[] mColor={"red","orange","yellow","green","cyan","blue","purple"};

        #region IEnumerable Members

        /*

        迭代器代碼使用 yield return 語句依次返回每個元素。yield break 將終止迭代。

        可以在類中實現多個迭代器。每個迭代器都必須像任何類成員一樣有唯一的名稱,

        並且可以在 foreach 語句中被用戶端代碼調用,如下所示:foreach(int x in SampleClass.Iterator2){}

        */

        public IEnumerator GetEnumerator()

        {

            for (int i = 0; i < mColor.Length; i++)

            {

                yield return mColor[i];

            }

        }

        #endregion

 

        //注意,這裡返回的是IEnumerable

        public System.Collections.IEnumerable DescColorIteration(int start, int end)

        {

            for (int i = 0; i <=end; i++)

            {

                yield return mColor[end-i];

            }

        }

        //在 foreach 迴圈的每次後續迭代(或對 IEnumerator.MoveNext 的直接調用)中,

        //下一個迭代器代碼體將從前一個 yield 語句之後開始,並繼續下一個語句直至到達迭代器體的結尾或遇到 yield break 語句

        public IEnumerable GetMutipleYied()

        {

            yield return "hello";

            yield return "I am";

            yield return "Jack";

            yield return "wang";

        }

    }

}

 

2. 輸出

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.