C#枚举器/迭代器
一、枚举器
1、为什么foreach可以顺序遍历数组?
因为foreach可以识别可枚举类型,通过访问数组提供的枚举器对象来识别数组中元素的位置从而获取元素的值并打印出来。
2、什么是枚举器?可枚举类型?
枚举结构里元素都是默认排序的,可以依靠识别元素的位置来获取值。可以把枚举器看做是集合的一个方法对象,他可以
依次返回所有的元素。而诸如此类给元素排好序的集合类型都可以算作可枚举类型。
3、具体过程如何实现?

二、可枚举类
枚举器继承了IEnumerable接口,包含了三个函数成员:Current、MoveNext、Reset。

可枚举类是指实现类IEnumerable接口的类,而这个接口只有一个成员——GetEnumerator方法,它负责返回对象的枚举器。
using System;
using System.Collections; class ColorEnumerator :IEnumerator
{
string[] _colors;
int _position = -1; public ColorEnumerator( string[] theColors ) // 构造函数
{
colors = new string[theColors.Length]; for (int i = 0;i < theColors.Length; i++ )
_colors[i] = theColors[i];
} public object Current // 实现Current
{
get
{
if (_position == -1 )
throw new InvalidOperationException();
if (_position >= _colors.Length )
throw new InvalidOperationException();
return _colors[_position];
}
} public bool MoveNext() // 实现MoveNext
{
if ( _position < _colors.Length - 1 )
{
_position ++;
return true;
}
else
return false;
} public void Reset() // 实现Reset
{
_position = -1;
}
} class Spectrum : IEnumerable
{
string[] Colors = { "violet", "blue", "cyan", "green","yellow", "orange", "red" }; public IEnumerator CetEnumerator()
{
return new ColorEnumerator( Colors );
}
} class Program
{
static void Main()
{
Spectrum spectrum = new Spectrum(); foreach( string color in spectrum )
Console.Writeline( color );
}
}
三、迭代器
一种便捷方式来创建枚举器跟迭代器,省略了手动编码实现可枚举类型跟枚举器。
常用的迭代器模式有两种:
1、不实现GetEnumerator方法,直接调用迭代器方法。
class Spectrum
{
string[] colors ={ "violet", "blue", "cyan”, “green", "yellow", "orange", "red" }; // 返回一个可枚举类型
public IEnumerable<string> UVtoIR()
{
for ( int i = 0; i < colors.Length; i++)
yield return colors[i]);
}
// 返回一个可枚举类型
public IEnumerable<string> IRtoU()
{
for ( int i = colors.Length -1; i >= 0; i--)
yleld return colors[i];
}
} class Program
{
static void Main()
{
Spectrum spectrum = new Spectrum(); foreach ( string color in spectrum.UVtoIR())
Console.Write("{0}",color );
Console.WriteLine(); foreach ( string color in spectrum.IRtoUV())
Console.Write("{O}",color );
Console.Writeline();
}
}
2、实现GetEnumerator方法,让类可枚举,调用迭代器的时候会自动生成IEnumerable的类实例
class Spectrum
{
bool _listFromUVtoIR;
string[] colors = { "violet", "blue", "cyan", "green","yellow", "orange", "red"); public Spectrum( bool listFromVtoIR )
{
_listFromlVtoIR = listFromUVtoIR;
} public IEnumerator<string> GetEnumerator()
{
return _listFromlVtoIR ? UVtoIR : IRtoUV;
} public IEnumerator<string> UVtoIR
{
get
{
for ( int i = 0; i < colors.Length; i++ )
yield return colors[i];
}
} public IEnumerator<string> IRtoUV
{
get
{
for ( int i = colors.Length - 1; i >= 0; i--)
yield return colors[i];
}
}
} class Program
{
static void Main()
{
Spectrum startUV = new Spectrum( true );
Spectrum startIR = new Spectrum( false ); foreach ( string color in startuV )
Console.Write("{0}", color );
Console.Writeline(); foreach ( string color in startIR )
Console.Write("{0}", color );
Console.WriteLine();
}
}
C#枚举器/迭代器的更多相关文章
- C#-14 枚举器和迭代器
一 枚举器和可枚举类型 当我们为数组使用foreach语句时,这个语句为我们依次取出了数组中的每一个元素. var arrInt = new int[] { 11, 12, 13, 14 }; for ...
- ruby迭代器枚举器
迭代器一个迭代器是一个方法,这个方法里面有yield语句,使用了yield的方法叫做迭代器,迭代器并非一定要迭代,与传递给这个方法的块进行数据传输 yield将数据传给代码快,代码块再把数据传输给yi ...
- ruby中迭代器枚举器的理解
参考<ruby编程语言>5.3迭代器和可枚举对象 迭代器一个迭代器是一个方法,这个方法里面有yield语句,这个方法里的yield语句,与传递给这个方法的块进行数据传输 yield将数据传 ...
- ruby迭代器iterator和枚举器Enumerator
编写自定义的迭代器 The defining feature of an iterator method is that it invokes a block of code associatedwi ...
- C#图解教程 第十八章 枚举器和迭代器
枚举器和迭代器 枚举器和可枚举类型 foreach语句 IEnumerator接口 使用IEnumerable和IEnumerator的示例 泛型枚举接口迭代器 迭代器块使用迭代器来创建枚举器使用迭代 ...
- C# 枚举器和迭代器
一.枚举器(enumerator)和可枚举类型(enumeration) 我们都知道foreach语句可以用来遍历数组中的元素,但你有没有想过为什么它可以被foreach处理呢? 这是因为数组可以按需 ...
- C#知识点-枚举器和迭代器
一.几个基本概念的理解 问题一:为什么数组可以使用foreach输出各元素 答:数组是可枚举类型,它实现了一个枚举器(enumerator)对象:枚举器知道各元素的次序并跟踪它们的位置,然后返回请求的 ...
- 设计模式 - 适配器模式(adapter pattern) 枚举器和迭代器 具体解释
适配器模式(adapter pattern) 枚举器和迭代器 具体解释 本文地址: http://blog.csdn.net/caroline_wendy 參考适配器模式(adapter patter ...
- 【Unity|C#】基础篇(20)——枚举器与迭代器(IEnumerable/IEnumerator)
[学习资料] <C#图解教程>(第18章):https://www.cnblogs.com/moonache/p/7687551.html 电子书下载:https://pan.baidu. ...
随机推荐
- install ubuntu on raspberry pi 4b
how to install 第一次连 wifi 时总会失败,需要 sudo reboot 重启后,就可以正常连接 当需要切换 wifi 时,修改 network-config 文件是无效的,需要 s ...
- 盘点微信小程序跨页面传值的若干方式
直接给大家上干货 1.跳转页面传递参数 pageA.wxml <button type="primary" bindtap="jumpTo">点击跳 ...
- Centos6添加防火墙端口 以及相关操作命令的使用
用命令 vim /etc/sysconfig/iptables 增加防火墙端口号:(添加你需要的端口号) service iptables start 启动防火墙 service iptables ...
- Acwing 428
可以找到规律,将第 N 项的 N 对应的二进制表示,转换为以 k 为基底的数即可. N=1=1 ----> 1 ----> \(a^b\) N=2=2 ----> 10 ----&g ...
- camunda开源流程引擎的数据库表结构介绍
Camunda bpm流程引擎的数据库由多个表组成,表名都以ACT开头,第二部分是说明表用途的两字符标识.本文以Camunda7.11版本为例,共47张表. ACT_RE_*: 'RE'表示流程资源存 ...
- .NET中测试代码运行时间
更新记录 本文迁移自Panda666原博客,原发布时间:2021年6月29日. 计算代码运行的时间,除了呆萌地用秒表去计时,或者可以通过Visual Studio来查看,还可以在.NET代码中使用St ...
- DevStream 成为 CNCF Sandbox 项目啦!- 锣鼓喧天、鞭炮齐鸣、红旗招展、忘词了。
开局两张图,内容全靠"编" 来,有图有真相! DevStream ️ CNCF DevStream joins CNCF Sandbox CNCF Cloud Native Int ...
- Metasploit msfvenom
一. msfvenom简介 msfvenom是msf payload和msf encode的结合体,于2015年6月8日取代了msf payload和msf encode.在此之后,metasploi ...
- 几百行代码实现一个 JSON 解析器
前言 之前在写 gscript时我就在想有没有利用编译原理实现一个更实际工具?毕竟真写一个语言的难度不低,并且也很难真的应用起来. 一次无意间看到有人提起 JSON 解析器,这类工具充斥着我们的日常开 ...
- Elasticsearch学习系列七(Es分布式集群)
核心概念 集群(Cluster) 一个Es集群由多个节点(Node)组成,每个集群都有一个共同的集群名称作为标识 节点(Node) 一个Es实例就是一个Node.Es的配置文件中可以通过node.ma ...