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);
}

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

相关推荐
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
神仙别闹5 天前
基于C#+MySQL实现(WinForm)个人聊天室软件
c#
kybs19915 天前
全球灾害数据分析可视化 毕业设计-附源码66794
vue.js·spring boot·mysql·安全·django·c#·asp.net
Polevne5 天前
C# SFTP客户端实现文件传输
c#·ssh
samble5 天前
从零搭建灌装监控系统(四):深色主题与样式系统,ResourceDictionary 统一管理
c#·wpf·mvvm·样式·工业控制
cjp5605 天前
024 . WPF MVVM类封装优化
c#
淡海水6 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
asdzx676 天前
如何使用 C# 提取 PPT 文本与图片
c#·ppt·提取文本
2501_930707786 天前
使用C#代码使用条件格式为 Excel 隔行设置颜色
c#·excel
何以解忧唯有撸码6 天前
【开源】c#造个轮子-日程安排工具
c#·自定义控件