C# IEnumerable<T>介绍

IEnumerable 是 C# 中的一个接口,它是 .NET Framework 中的集合类型的基础。任何实现了 IEnumerable 接口的对象都可以进行 foreach 迭代。

IEnumerable 只有一个方法,即 GetEnumerator,该方法返回一个 IEnumerator 对象。IEnumerator 对象用于迭代集合,它提供了 MoveNext 方法(用于移动到集合的下一个元素),Current 属性(获取当前元素)和 Reset 方法(将枚举器设置回其初始位置,但这个方法通常不会被实现或使用)。

在大多数情况下,你不需要直接实现 IEnumerable 或 IEnumerator。相反,你可以使用 yield return 语句让编译器为你生成这些方法。

比如使用IEnumerable实现一个生成斐波那契数列,下面这个例子展示了如何实现一个这样的生成器:

csharp 复制代码
using System;
using System.Collections.Generic;

public class FibonacciGenerator : IEnumerable<long>
{
    private readonly int _count;

    public FibonacciGenerator(int count)
    {
        _count = count;
    }

    public IEnumerator<long> GetEnumerator()
    {
        long current = 1, previous = 0;
        for (int i = 0; i < _count; i++)
        {
            long temp = current;
            current = previous + current;
            previous = temp;
            yield return previous;
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

在上述代码中,FibonacciGenerator 类实现了 IEnumerable<long> 接口。GetEnumerator 方法是 IEnumerable<T> 接口的一部分,它返回一个 IEnumerator<T>,这个 IEnumerator<T> 会生成斐波那契数列。

当你创建一个 FibonacciGenerator 实例并开始遍历它时,GetEnumerator 方法会被调用,然后返回的 IEnumerator<long> 会被用来生成斐波那契数列的值。

例如,以下代码将打印前10个斐波那契数:

csharp 复制代码
foreach (var num in new FibonacciGenerator(10))
{
    Console.WriteLine(num);
}

这种方法的优势在于,它只在需要下一个斐波那契数时才计算它,而不是一次性计算所有的斐波那契数。这使得它能有效地处理大规模的数据。

相关推荐
暴走约伯17 小时前
【VFX工具链源码拆解 09】终极工业化闭环:基于 ID 规则驱动的全自动场景建档、骨骼挂载与男转女场景迁移
unity·c#·游戏引擎·材质
用户788477316342 天前
WinForms 迁移 WPF:Upgrade Assistant 覆盖 30%,剩下 70% 我手写了六周
c#
寂寞的船2 天前
【Unity知识速递】第13期 Unity 内存泄漏排查实战:从 Memory Profiler 到 Lua 引用泄漏的生产级全链路诊断
unity·junit·c#·游戏引擎·lua
用户3721574261352 天前
C# 提取 PDF 附件:包括文档附件和页面注释附件
c#
寂寞的船2 天前
【Unity Bug挑战】第12期 Awaitable 二次 await 死锁之谜 —— 为什么同一个异步操作等两次就卡死?
unity·c#·游戏引擎·bug
huaqianzkh4 天前
WinForm C#:循环修改控件UI闪烁卡顿?SuspendLayout / ResumeLayout 与 BeginUpdate 优化
开发语言·ui·c#
用户3721574261355 天前
C# 实现 Excel 单元格保护:锁定公式并允许编辑指定区域
c#·ai编程·编程语言
公子小六5 天前
基于.NET的Windows窗体编程之WinForms数据持久化(1)
windows·microsoft·c#·.net·winforms
三雷科技5 天前
第6章第4节:自定义分词器
开发语言·c#
zhanghaha13145 天前
C# 系列教程_12 字符串 string 保姆级系统教程(面向新手,大量示例 + 原理讲解)
开发语言·数据库·c#