IEnumerable与IEnumerator接口深度解析
概述
在.NET框架中,IEnumerable和IEnumerator是实现集合遍历的基础接口。它们位于System.Collections命名空间下,是实现foreach循环的背后机制。
IEnumerable接口
IEnumerable接口表示一个可枚举的集合类型。该接口仅包含一个方法:
- GetEnumerator():返回集合的枚举器实例
实现此接口的类可以通过foreach语句进行迭代遍历。
IEnumerator接口
IEnumerator接口提供了枚举器的基本功能,包含三个成员:
- Current:只读属性,返回当前枚举位置的元素
- MoveNext():方法,将枚举器推进到下一元素,返回是否成功
- Reset():方法,将枚举器重置到初始位置
注意:枚举器的初始位置在第一个元素之前,因此首次调用MoveNext()后才会指向第一个元素。
基本使用示例
以下示例展示如何直接使用枚举器遍历数组:
class EnumeratorDemo
{
static void Main(string[] args)
{
int[] numbers = { 5, 10, 15, 20, 25 };
IEnumerator iterator = numbers.GetEnumerator();
while (iterator.MoveNext())
{
int value = (int)iterator.Current;
Console.WriteLine($"当前值: {value}");
}
Console.ReadKey();
}
}
自定义集合实现
以下示例展示如何创建自定义可枚举集合:
class Program
{
static void Main(string[] args)
{
WeekDays week = new WeekDays();
foreach (string day in week)
{
Console.WriteLine(day);
}
Console.ReadKey();
}
}
class WeekDays : IEnumerable
{
private string[] days = { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日" };
public IEnumerator GetEnumerator()
{
return new WeekDaysIterator(days);
}
}
class WeekDaysIterator : IEnumerator
{
private string[] collection;
private int currentIndex;
public WeekDaysIterator(string[] source)
{
collection = new string[source.Length];
Array.Copy(source, collection, source.Length);
currentIndex = -1;
}
public object Current
{
get
{
if (currentIndex == -1)
{
throw new InvalidOperationException("枚举尚未开始");
}
if (currentIndex >= collection.Length)
{
throw new InvalidOperationException("枚举已结束");
}
return collection[currentIndex];
}
}
public bool MoveNext()
{
if (currentIndex < collection.Length - 1)
{
currentIndex++;
return true;
}
return false;
}
public void Reset()
{
currentIndex = -1;
}
}
泛型版本对比
.NET还提供了泛型版本的接口:IEnumerable<T>和IEnumerator<T>,位于System.Collections.Generic命名空间。主要区别:
| 特性 | 非泛型版本 | 泛型版本 |
|---|---|---|
| Current属性类型 | Object | T(具体类型) |
| 类型安全 | 需要装箱拆箱 | 编译时类型检查 |
| 性能 | 较低 | 较高 |
泛型版本的优势在于避免了装箱拆箱操作,提供了编译时的类型安全检查,实际开发中推荐优先使用泛型版本。