• C# IEnumerable<T>介绍


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

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

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

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

    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();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

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

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

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

    foreach (var num in new FibonacciGenerator(10))
    {
        Console.WriteLine(num);
    }
    
    • 1
    • 2
    • 3
    • 4

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

  • 相关阅读:
    一文彻底搞懂性能测试
    反射技巧让你的性能提升N倍
    高云FPGA系列教程(6):ARM定时器使用
    MySQL:索引的基础知识
    C#小项目之记事本
    【Java 设计模式】简单工厂模式 & 静态工厂模式
    iwemeta元宇宙:阿里首任COO:如何打造销售铁军
    ISCSI:后端卷以LVM 的方式配置 ISCSI 目标启动器
    windows 系统下 workerman 在同一个运行窗口中开启多个 websocket 服务
    3万字智慧交通数字化建设方案
  • 原文地址:https://blog.csdn.net/yao_hou/article/details/134485479