首页 > 编程语言 >C#中的迭代器

C#中的迭代器

时间:2024-01-16 12:33:06浏览次数:22  
标签:return string 迭代 C# colors 枚举 public

枚举器和迭代器

使用foreach语句迭代遍历

int[] arr = { 9, 12, 43, 10, 6, 5 };
foreach(int e in arr) Console.WriteLine(e);

数组之所以这么可以做,原因是数组可以按需提供一个叫做枚举器的对象,枚举器可以依次返回请求数组中的元素。对于有枚举器的类型而言,必须有一种方式来获取它,获取对象枚举器的方法是调用对象的GEnumertaor方法。实现GetEnumeratot方法的类型可叫做可枚举类型enumerable type,其中数组是可枚举类型。

IEnumerator接口

实现了IEnumerator接口的枚举器包含了3个函数成员:Current、MoveNext、Rest:

  • Current是返回序列中当前位置项的属性。
  • MoveNext,把枚举器位置前进到集合的下一个位置,如果新的位置是有效的,返回true,否则(例如到达了尾部)无效。
  • Reset是把位置重置到原始状态的方法。
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
IEnumerator ie = arr.GetEnumerator();	// 获取枚举器
while (ie.MoveNext()) Console.WriteLine($"{ie.Current}");	// 获取当前项并输出

IEnumerable接口

可枚举类是指实现了IEnumerable接口的类,IEnumerable接口只有一个成员GetEnumerator方法,它返回对象的枚举器,例如下面的例子:

using System.Collections;

namespace CSharpProject1;

class MyColor : IEnumerable
{
    private string[] Colors = { "RED", "YELLOW", "BLUE" };
    public IEnumerator GetEnumerator()
    {
        return new ColorEnumerator(Colors);
    }
}

class ColorEnumerator:IEnumerator
{
    private string[] colors;
    private int position = -1;

    public ColorEnumerator(string[] colors)
    {
        this.colors = new string[colors.Length];
        for (int i = 0; i < colors.Length; i++) this.colors[i] = colors[i];
    }
    
    public bool MoveNext()
    {
        if (position < this.colors.Length - 1)
        {
            position++;
            return true;
        }
        else return false;
    }

    public void Reset()
    {
        position = -1;
    }

    public object Current
    {
        get
        {
            if (position == -1) throw new InvalidCastException();
            if (position > this.colors.Length) throw new InvalidOperationException();
            return colors[position];
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyColor mc = new MyColor();
        foreach (string color in mc) Console.WriteLine(color);
    }
}
D:/RiderProjects/CSharpProject1/CSharpProject1/bin/Debug/net8.0/CSharpProject1.exe
RED
YELLOW
BLUE  

Process finished with exit code 0.

迭代器

迭代器是更先进的枚举器:

using System.Collections;

namespace CSharpProject1;

class MyClass
{
    public IEnumerator<string> GetEnumerator()
    {
        return BlackAndWhite(); // 返回迭代器
    }

    public IEnumerator<string> BlackAndWhite()  //迭代器
    {
        yield return "black";
        yield return "gray";
        yield return "white";
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass mc = new MyClass();
        foreach (string e in mc) Console.WriteLine($"{e}");
    }
}

标签:return,string,迭代,C#,colors,枚举,public
From: https://www.cnblogs.com/lilyflower/p/17967411

相关文章

  • 无涯教程-SQL - Truncate(清空表)
    SQLTRUNCATETABLE命令用于从现有表中删除完整数据。Truncate-语法TRUNCATETABLE命令的基本语法如下。TRUNCATETABLEtable_name;Truncate-示例考虑具有以下记录的CUSTOMERS表-+----+----------+-----+-----------+----------+|ID|NAME|AGE|ADDRES......
  • Road Extraction from Remote Sensing Images Using the Inner Convolution Integrate
    landbench里面,李老师提到的encode-decode。remotesensing,大类是2区,小类是2到3区。分类的题目:“利用内部卷积集成编码器-解码器网络和定向条件随机场从遥感图像中提取道路”(pdf)“RoadExtractionfromRemoteSensingImagesUsingtheInnerConvolutio......
  • 【pwn】wustctf2020_closed --exec重定向
    这道题先来看一下ida这道题的代码逻辑很简单,首先关闭了标准输出和错误输出那可以将标准输出重定向到标准输入exec1>&0是一种Shell命令行中的重定向语法,用于将标准输出(文件描述符1)重定向到标准输入(文件描述符0)。在LinuxShell中,每个进程都有三个默认的标准文件描述符:标准......
  • docker 设置 ulimit
    一、通过dockerrun–ulimit参数设置这个容器的ulimit值dockerrun--ulimitnofile=1024:1024--rmdebiansh-c"ulimit-n"二、通过配置daemon.json配置默认值配置nofile{"default-ulimits":{"nofile":{......
  • c++重载
    注意:函数的返回值不可以作为函数重载的条件函数重载的注意事项1.引用作为重载的条件2.函数重载遇到函数默认参数......
  • Atcoder Beginner Contest 330 题解
    AtCoderBeginnerContest330题解A-CountingPasses签到voidShowball(){intn,l;cin>>n>>l;intcnt=0;for(inti=0;i<n;i++){intx;cin>>x;cnt+=(x>=l);}cout<<cnt<<endl;}B-Minimize......
  • 基于标签值分布的强化学习推荐算法(Reinforcement Learning Recommendation Algorithm
    前言看论文的第三天,坚持下去。慢慢来,比较快。——唐迟本文基于2023年6月28日发表在MATHEMATICS上的一篇名为“基于标签值分布的强化学习推荐算法”(ReinforcementLearningRecommendationAlgorithmBasedonLabelValueDistribution)的文章。文章提出了一种基于标签分布......
  • tcpdump+wireshark抓包分析
    目录tcpdump核心参数详解tcpdump的输出理解输出结构flag标识符常规过滤规则基于IP地址过滤基于网段过滤基于端口过滤基于协议进行过滤可选参数解析不解析域名提升速度结果输出到文件从文件中读取数据指定抓取个数指定设备口过滤规则组合tcpdump是linux下的一个命令行抓包工具wir......
  • 使用s3cmd工具访问对象存储
      近两天在测试某cloud的对象存储,使用客户端s3cmd工具在centos下部署。部署过程和常用功能如下:某cloud的对象存储下载和安装下载地址:https://s3tools.org/download   本次使用的是s3cmd-2.4.0.tar.gz文件。安装先解决依赖关系---- yuminstallpython-dateutil,否则会提示......
  • Ch01 投资与量化投资
    1.1量化投资 量化投资是一种投资交易策略。量化投资策略是利用统计学、数学、信息技术、人工智能等方法取代人工作出决策,通过模型完成股票交易来构建投资组合。利用计算机技术和数学模型去实现投资策略的过程。一般情况下,市场研究、基本面分析、选股、择时、下单等都可以由计算......