枚举器
发表于:2025-10-13 | 分类: Dotnet
字数统计: 282 | 阅读时长: 1分钟 | 阅读量:

枚举器

标准化了集合的遍历过程,而无需关心集合的具体实现细节。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\IEnumerator.cs
namespace System.Collections
{
// 所有枚举器的基础接口,提供迭代集合的简单方法
public interface IEnumerator
{
// 将枚举器的位置推进到集合的下一个元素,初始位置在第一个元素之前,返回true表示有元素
bool MoveNext();

// 获取枚举器当前指向的元素,仅在 MoveNext() 返回 true 后有效
object Current { get; }

// 将枚举器重置到初始位置(集合的第一个元素之前),以便重新遍历。
void Reset();
}
}

对应的泛型接口:

1
2
3
4
5
6
7
8
9
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\Generic\IEnumerator.cs
namespace System.Collections.Generic
{
public interface IEnumerator<out T> : IDisposable, IEnumerator
{
new T Current { get; }
}
}

字典枚举器接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\Generic\IDictionaryEnumerator.cs
namespace System.Collections
{
// 序列化访问字典的枚举器
public interface IDictionaryEnumerator : IEnumerator
{
// 当前元素的key
object Key { get; }

// 当前元素的value
object? Value { get; }

// 当前entry,防止装箱
DictionaryEntry Entry { get; }
}
}
上一篇:
列表
下一篇:
相等性比较