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


    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. 输出

    image

    扫码关注公众号,了解更多管理,见识,育儿等内容

    作者: 王德水
    出处:http://www.cnblogs.com/cnblogsfans
    版权:本文版权归作者所有,转载需经作者同意。

  • 相关阅读:
    整数
    mysql-5.7.13-win32 安装
    Flex air修改外部xml文件 (转)
    JAVA 取得当前目录的路径/Servlet/class/文件路径/web路径/url地址
    C#中&和&&的区别
    百度UEditor1.4.3编辑器和asp.net MVC 5结合
    ASP.NET MVC ajax数组,模型绑定问题。
    MEF依赖注入无法在在构造函数中使用的解决办法
    AJaxFileUpload 文件上传<pre>,json字符串为空解决方法
    C#中字符串转换为IPAdress
  • 原文地址:https://www.cnblogs.com/cnblogsfans/p/1222099.html
Copyright © 2020-2023  润新知