C# IEnumerable

发布于:2023-12-24 11:43:02

在C#中,IEnumerable 是一个接口,它定义了枚举(迭代)一个集合中的对象的方法。IEnumerable 接口是 .NET Framework 中所有集合类的基类接口之一。通过实现 IEnumerable 接口,集合类可以提供一种方法来遍历其元素。

IEnumerable 接口包含一个名为 GetEnumerator 的方法,该方法返回一个 IEnumerator 对象,该对象用于遍历集合中的元素。

下面是一个简单的例子,展示了如何使用 IEnumerable 和 IEnumerator

using System;  
using System.Collections;  
  
class Program  
{  
    static void Main()  
    {  
        // 创建一个自定义的简单集合  
        SimpleCollection<int> collection = new SimpleCollection<int>();  
          
        // 向集合中添加一些元素  
        collection.Add(1);  
        collection.Add(2);  
        collection.Add(3);  
          
        // 使用 IEnumerable 和 IEnumerator 遍历集合中的元素  
        foreach (int item in collection)  
        {  
            Console.WriteLine(item);  
        }  
    }  
}  
  
// 自定义的简单集合类,实现了 IEnumerable 接口  
public class SimpleCollection<T> : IEnumerable<T>  
{  
    private readonly List<T> _items = new List<T>();  
      
    public void Add(T item) => _items.Add(item);  
      
    public IEnumerator<T> GetEnumerator() => _items.GetEnumerator();  
      
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); // 实现非泛型的 IEnumerable 接口方法  
}

在上面的例子中,我们创建了一个简单的泛型集合 SimpleCollection<T>,它实现了 IEnumerable<T> 接口。这意味着我们可以使用 foreach 循环来遍历集合中的元素。在 Main 方法中,我们创建了一个 SimpleCollection<int> 的实例,并向其中添加了一些整数。然后我们使用 foreach 循环遍历并打印出集合中的每个元素。

阅读 168+

一片空白

父爱如山,不善表达。回想十多年前,总记得父亲有个宽厚的肩膀,小小的自己跨坐在上面,越过人山人海去看更广阔的天空,那个时候期望自己有一双翅膀,能够像鸟儿一样飞得高,看得远。虽然父亲有时会和自己开玩笑,但在做错事的时候会受到严厉的训斥。父亲有双粗糙的大手掌。