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/archive/2008/06/14/1222099.html如需转载请自行联系原作者


王德水

相关文章
|
22天前
|
C#
C#拾遗补漏之goto跳转语句
在我们日常工作中常用的C#跳转语句有break、continue、return,但是还有一个C#跳转语句很多同学可能都比较的陌生就是goto,今天大姚带大家一起来认识一下goto语句及其它的优缺点。
|
22天前
|
开发框架 人工智能 .NET
C#/.NET/.NET Core拾遗补漏合集(持续更新)
在这个快速发展的技术世界中,时常会有一些重要的知识点、信息或细节被忽略或遗漏。《C#/.NET/.NET Core拾遗补漏》专栏我们将探讨一些可能被忽略或遗漏的重要知识点、信息或细节,以帮助大家更全面地了解这些技术栈的特性和发展方向。
|
存储 .NET C#
C#基础拾遗系列之一:先看懂IL代码
原文:C#基础拾遗系列之一:先看懂IL代码 一、前言 首先,想说说为什么要写这样系列的文章,有时候在和同事朋友聊天的时候,经常会听到这样的话题: (1)在这家公司没什么长进,代码太烂,学不到东西。(你有没有想想框架为什么这样写,代码还可以怎么去优化,比如公司使用Dapper,源码研究过没以及这样...
1951 0