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

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

相关推荐
xiaowu08014 小时前
策略模式-不同的鸭子的案例
开发语言·c#·策略模式
VisionPowerful17 小时前
九.弗洛伊德(Floyd)算法
算法·c#
ArabySide17 小时前
【C#】 资源共享和实例管理:静态类,Lazy<T>单例模式,IOC容器Singleton我们该如何选
单例模式·c#·.net core
gc_229919 小时前
C#测试调用OpenXml操作word文档的基本用法
c#·word·openxml
almighty271 天前
C#海康车牌识别实战指南带源码
c#·海康车牌识别·c#实现车牌识别·车牌识别源码·c#车牌识别
c#上位机1 天前
wpf之TextBlock
c#·wpf
almighty271 天前
C# WinForm分页控件实现与使用详解
c#·winform·分页控件·c#分页·winform分页
almighty271 天前
C#实现导入CSV数据到List<T>的完整教程
c#·csv·格式转换·c#导入数据·csv数据导入
程序猿多布2 天前
Lua和C#比较
c#·lua
csdn_aspnet2 天前
使用 MongoDB.Driver 在 C# .NETCore 中实现 Mongo DB 过滤器
mongodb·c#·.netcore