当前位置:网站首页>C# 迭代器的实现
C# 迭代器的实现
2022-07-26 01:49:00 【廷益--飞鸟】

1.代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson23_Iterator
{
class Program
{
#region 一、迭代器是什么
// 迭代器模式 提供一个方法顺序访问一个聚合对象中的 各个元素
// 可以使用foreach遍历的类,都实现了迭代器
#endregion
#region 二、标准迭代器需要实现什么
// 关键接口:IEnumerable,
// 命名空间:using System.Collections;
class MyList : IEnumerable, IEnumerator
{
private int[] list;
private int cursor = -1;
public MyList()
{
list = new int[] {
1, 2, 3, 4};
}
// foreach 本质
// 1.调用 GetEnumerator 方法 获取
// 2.调用 MoveNext()
// 3.MoveNext() 返回true 获取到 Current
// 再次MoveNext()
// 如果返回 False 结束 并调用 Reset()
#region IEnumerable
public IEnumerator GetEnumerator()
{
// 第一次光标位置
Reset();
// 返回自己的对象
return this;
}
#endregion
#region IEnumerator
// 返回 聚合中的 对象
public object Current
{
get
{
return list[cursor];
}
}
// 移动光标
public bool MoveNext()
{
// 移动光标
++cursor;
// 溢出则不合法
return cursor < list.Length;
}
// 重置光标
public void Reset()
{
cursor=-1;
}
#endregion
}
#endregion
#region 三、使用yield return 实现迭代器
// 1.继承 IEnumerable 一个接口
// 2. 使用 yield return 返回item即可
class CustomList : IEnumerable
{
private int[] list;
public CustomList()
{
this.list = new int[] {
5, 6, 7, 8 };
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < list.Length; i++)
{
// 语法糖 编译后具体实现为 传统方式
yield return this.list[i];
}
}
}
#region 四、泛型迭代器
// 1.继承 IEnumerable 一个接口
// 2. 使用 yield return 返回item即可
class TempleList<T> : IEnumerable
{
private T[] arry;
public TempleList(params T[] arry)
{
this.arry = arry;
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < this.arry.Length; i++)
{
yield return this.arry[i];
}
}
}
#endregion
#endregion
static void Main(string[] args)
{
Console.WriteLine("=========迭代器===========");
MyList mylist = new MyList();
Console.WriteLine("=========1.传统实现===========");
foreach (int item in mylist)
{
Console.WriteLine(item);
}
Console.WriteLine("=========2.yield 实现===========");
CustomList customList = new CustomList();
foreach (int item in customList)
{
Console.WriteLine(item);
}
Console.WriteLine("=========3.yield 实现泛型迭代器===========");
TempleList<string> tempList = new TempleList<string>("AAA", "BBB", "CCC");
foreach (var item in tempList)
{
Console.WriteLine(item);
}
// 总结
// 迭代器就是 可以直接通过 foreach 遍历对象,而不需要了解内部结果
// 主要的实现方式有:
// 1.传统方法 继承两个接口IEnumerable, IEnumerator
// 2.yield return 方式实现 继承 IEnumerable
Console.ReadLine();
}
}
}

边栏推荐
- 元素和小于等于阈值的正方形的最大边长(来源:力扣(LeetCode))
- “蔚来杯“2022牛客暑期多校训练营2 K.[Link with Bracket Sequence I] 括号序列 DP
- Go operation excel library excel use
- [independent station construction] Shopify seller: learn these points and double the sales volume of online stores!
- “蔚来杯“2022牛客暑期多校训练营2 H.[Take the Elevator] 维护线段
- How to do Taobao live broadcast and how to do the anchor to drain and sell products
- How to display numbers / English time in Excel
- Stack Title: basic calculator
- Summary after reading "poor dad and rich dad"
- Silicon Valley classroom - official account cloud on demand Silicon Valley classroom microservice project practical notes
猜你喜欢

AUTOCAD——计算面积的方法

Typora expiration solution, what if typora can't open
![[unity] random generation of two-dimensional cave map](/img/ec/7433f6e942fc3d0b03cac37ac87e7b.png)
[unity] random generation of two-dimensional cave map

SVN version control branch and merge function use

【独立站建设】shopify卖家:学会这几点,网上商店销量翻倍!

Pt onnx ncnn conversion problem record (followed by yolov5 training)

Protect syslog servers and devices

Image batch processing Gaussian filter noise reduction + peak signal-to-noise ratio calculation
![[independent station construction] Shopify seller: learn these points and double the sales volume of online stores!](/img/52/8c1520db38ffa8927e975b6f244a65.png)
[independent station construction] Shopify seller: learn these points and double the sales volume of online stores!

Maximum side length of elements and squares less than or equal to the threshold (source: leetcode)
随机推荐
The import and Export button of Damon database table is gray, and the DMP file cannot be imported
C language enumeration types and unions
Recommend a super good UI automation tool: uiautomator2!
Quickly create a topic folder
SVN版本控制分支、合并功能使用
在Anaconda 中安装和使用R
ABC find 4-cycle (pigeon nest theorem)
D - Dire Wolf (interval DP)
Spark-SQL中根据年月日显示周几用date_format(date,‘u‘)
Worthington木瓜蛋白酶丨从纯化的蛋白聚糖生产糖肽(附文献)
Speech comprehension center comprehension summary
【独立站建设】shopify卖家:学会这几点,网上商店销量翻倍!
Mysql_ Note1
IP address of the network
pt-onnx-ncnn转换的问题记录(接yolov5训练)
[unity] random generation of two-dimensional cave map
"Weilai Cup" 2022 Niuke summer multi school training camp 2 h.[take the elevator] maintenance section
zeromq浅析
Stack Title: basic calculator
劳驾问一下各位老师 oracle 到pg cdc oracle 那边字段大写 pg 这边小写 同