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. ...
随机推荐
- 455. Assign Cookies - LeetCode
Question 455. Assign Cookies Solution 题目大意:数组g的大小表示有几个小孩,每个元素表示小孩的食量,数组s的大小表示有多少个饼干,每个元素的大小表示每个饼干的大小 ...
- 好客租房25-react中的事件处理(事件对象)
3.2事件对象 可以通过事件处理程序的参数 React中的事件对象叫做:合成事件(对象) 合成事件:兼容所有浏览器 //导入react import React from 'react' ...
- 好客租房8-React基础阶段总结
React总结 1react是构建用户组件的javascript库 2使用react是,推荐使用脚手架方式 3初始化项目命令:npx create-react-app my-app 4启动项目命令:y ...
- python之数据类型的内置方法(str, list)
目录 字符串的内置方法 移除首尾指定字符 字母大小写相关操作 判断字符串的开头或结尾是否是指定字符 字符串特殊的输出方法 拼接字符串 替换指定字符 判断是否是纯数字 查找指定字符对应的索引值 文本位置 ...
- 新建Vue项目记得几个配置
1.在APP.vue文件夹中进行CSS初始化 2.下载vuex,vue-router,并配置 3.关闭语法检查vue.config.js 4.按需引入组件库
- vue新手入门之使用vue框架搭建用户登录注册案例,手动搭建webpack+Vue项目(附源码,图文详解,亲测有效)
前言 本篇随笔主要写了手动搭建一个webpack+Vue项目,掌握相关loader的安装与使用,包括css-loader.style-loader.vue-loader.url-loader.sass ...
- Es图形化软件使用之ElasticSearch-head、Kibana,Elasticsearch之-倒排索引操作、映射管理、文档增删改查
今日内容概要 ElasticSearch之-ElasticSearch-head ElasticSearch之-安装Kibana Elasticsearch之-倒排索引 Elasticsearch之- ...
- JAVA - 线程同步和线程调度的相关方法
JAVA - 线程同步和线程调度的相关方法 wait():使一个线程处于等待(阻塞)状态,并且释放所持有的对象的锁:wait是Object类的方法,对此对象调用wait方法导致本线程放弃对象锁,进入等 ...
- sqlmap自动检测漏洞并进行渗透
使用案例靶场为上篇文章介绍的封神台---靶场 https://hack.zkaq.cn/ 提示:采用开源靶场里面的猫舍进行渗透注入,仅用于安全防范无安全侵犯 1.首先检测是否已经安装成功sqlma ...
- C#中常用的目录|文件|路径信息操作
更新记录 本文迁移自Panda666原博客,原发布时间:2021年5月16日. 说明 .NET的类库API设计的非常优秀,再加上文档docs.com写的非常优秀,写代码给人一种十分优雅的感觉. 获得当 ...