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

枚举

所有实现了 IEnumerable 接口的类型都是 可枚举的

所有集合都可枚举:

1
public interface ICollection : IEnumerable

源码:

1
2
3
4
5
6
7
8
9
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\IEnumerable.cs
namespace System.Collections
{
public interface IEnumerable
{
// 返回对象的枚举器,用于提供一种方式访问集合的所有元素
IEnumerator GetEnumerator();
}
}

对应的泛型接口:

1
2
3
4
5
6
7
8
9
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\Generic\IEnumerable.cs
namespace System.Collections.Generic
{
// 支持foreach语句都需要实现该接口
public interface IEnumerable<out T> : IEnumerable
{
new IEnumerator<T> GetEnumerator();
}
}
上一篇:
比较
下一篇:
集合