C#【进阶】迭代器

迭代器

文章目录

      • 1、迭代器概念
      • 2、标准迭代器的实现方法
      • [3、用yield return 语法糖实现迭代器](#3、用yield return 语法糖实现迭代器)
      • [4、用yield return 语法糖为泛型类实现迭代器](#4、用yield return 语法糖为泛型类实现迭代器)

1、迭代器概念

c 复制代码
迭代器(iterator) 又称光标(cursor)
是程序设计的软件设计模式
迭代器提供一个方法顺序访问一个聚合对象中的各个元素
而又不暴露其内部的标识

在表现效果上看
是可以在容器对象(例如链表或数组)上遍历访问的接口
设计人员无需关心容器对象的内存分配的实现细节
可以用foreach遍历的类,都是实现了迭代器的

2、标准迭代器的实现方法

csharp 复制代码
继承IEnumerable, IEnumerator
using System.Collections;

CustomList lists = new CustomList();
//foreach本质
//1、先获取in后面这个对象的IEnumerator
//会调用对象其中的GetEnumerator方法来获取
//2、执行得到这个IEnumerator对象中的MoveNext方法
//3、只要MoveNext方法的返回值是true,就会去得到Current
//然后赋值给item
foreach (var item in lists)
{
    Console.WriteLine(item);
}

class CustomList : IEnumerable, IEnumerator
{
    private int position = -1;
    private int[] list;
    public CustomList()
    {
        list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    }

    public object Current {
        get { return list[position]; }
    }

    public IEnumerator GetEnumerator()
    {
        Reset();
        return this;
    }

    public bool MoveNext()
    {
        position++;
        return position < list.Length;
    }

    //reset重置光标位置,写在IEnumerator中
    public void Reset()
    {
        position = -1;
    }
}

3、用yield return 语法糖实现迭代器

csharp 复制代码
yield return 是C#提供的语法糖
语法糖主要作用就是将复杂逻辑简单化,可以增加程序的可读性
    
CustomList list = new CustomList();
foreach (var item in list)
{
Console.WriteLine(item);
}
class CustomList : IEnumerable
{
    private int[] list;
    public CustomList()
    {
        list = new int[] { 1, 2, 3 };
    }
    public IEnumerator GetEnumerator()
    {
        for (int i = 0; i < list.Length; i++)
        {
            //配合迭代器使用
            yield return list[i];
        }
    }
}

4、用yield return 语法糖为泛型类实现迭代器

csharp 复制代码
CustomList<string> array = new CustomList<string>("aaa","bbb","ccc");
foreach (var item in array)
{
    Console.WriteLine(item);
}
class CustomList<T> : IEnumerable
{
    private T[] array;
    public CustomList(params T[] array)
    {
        this.array = array;
    }
    public IEnumerator GetEnumerator()
    {
        for (int i = 0; i < array.Length; i++)
        {
            yield return array[i];
        }
    }
}
相关推荐
小灰灰搞电子3 小时前
Rust+Slint 实现动态消息提示框源码分享
开发语言·后端·rust
传奇开心果编程5 小时前
【Rust入门知识点学与练】第21课:Trait 进阶 Advanced Traits
开发语言·学习·rust
新时代牛马5 小时前
字符设备驱动完整篇:从 cdev_add、file_operations 到chrdev_open 与排障
开发语言·python
swordbob5 小时前
ReentrantLock 与 AQS 完整学习手册
java·开发语言
淡海水6 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
白山编程大哥6 小时前
Java OutputStreamWriter 详解:从字符到字节的桥梁
java·开发语言·python
shmily麻瓜小菜鸡7 小时前
JavaScript / TypeScript 易踩坑知识点 —— 异步编程类
开发语言·javascript·typescript
七夜zippoe7 小时前
为什么 2026 年每个 Java 团队都该懂 AI Agent
java·开发语言·人工智能
znnnk7 小时前
【Python】GUI 开发从入门到实战(三):PyQt/PySide 进阶之路
开发语言·python·pyqt
Despacito10068 小时前
Java后端性能探查工具速查表
java·开发语言