在C#中如何遍历所有枚举值

在C#中如何遍历所有枚举值

技术背景

在C#编程中,枚举(Enum)是一种值类型,它用于定义一组命名的常量。有时我们需要遍历枚举中的所有值,比如在显示所有可能的选项、进行批量处理等场景下。

实现步骤

1. 使用Enum.GetValues方法

可以使用Enum.GetValues方法获取指定枚举类型的所有值。示例代码如下:

1
var values = Enum.GetValues(typeof(Foos));

2. 使用类型化版本

如果想得到强类型的枚举值集合,可以进行类型转换:

1
var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();

3. 封装辅助函数

为了方便使用,可以封装一个泛型辅助函数:

1
2
3
4
5
public static class EnumUtil {
public static IEnumerable<T> GetValues<T>() {
return Enum.GetValues(typeof(T)).Cast<T>();
}
}

使用方式如下:

1
var values = EnumUtil.GetValues<Foos>();

4. 改进泛型辅助函数

为了确保传入的类型是枚举类型,可以添加类型检查:

1
2
3
4
5
6
7
8
9
10
private static IEnumerable<T> GetEnumValues<T>()
{
// Can't use type constraints on value types, so have to do check like this
if (typeof(T).BaseType != typeof(Enum))
{
throw new ArgumentException("T must be of type System.Enum");
}

return Enum.GetValues(typeof(T)).Cast<T>();
}

5. 遍历枚举值示例

以下是一个完整的遍历枚举值并输出的示例:

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
using System;
using System.Collections.Generic;
using System.Linq;

public enum DaysOfWeek
{
monday,
tuesday,
wednesday
}

class Program
{
static void Main(string[] args)
{
foreach (int value in Enum.GetValues(typeof(DaysOfWeek)))
{
Console.WriteLine(((DaysOfWeek)value).ToString());
}

foreach (string value in Enum.GetNames(typeof(DaysOfWeek)))
{
Console.WriteLine(value);
}
Console.ReadLine();
}
}

核心代码

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
30
31
32
33
34
35
36
37
38
39
40
41
42
// 辅助函数
public static class EnumUtil {
public static IEnumerable<T> GetValues<T>() {
return Enum.GetValues(typeof(T)).Cast<T>();
}
}

// 改进的辅助函数
private static IEnumerable<T> GetEnumValues<T>()
{
if (typeof(T).BaseType != typeof(Enum))
{
throw new ArgumentException("T must be of type System.Enum");
}

return Enum.GetValues(typeof(T)).Cast<T>();
}

// 遍历枚举示例
public enum DaysOfWeek
{
monday,
tuesday,
wednesday
}

class Program
{
static void Main(string[] args)
{
foreach (int value in Enum.GetValues(typeof(DaysOfWeek)))
{
Console.WriteLine(((DaysOfWeek)value).ToString());
}

foreach (string value in Enum.GetNames(typeof(DaysOfWeek)))
{
Console.WriteLine(value);
}
Console.ReadLine();
}
}

最佳实践

  • 当需要多次遍历枚举值时,封装一个辅助函数可以提高代码的复用性。
  • 在使用泛型辅助函数时,添加类型检查可以避免传入非枚举类型导致的错误。

常见问题

  • 传入非枚举类型:如果不进行类型检查,传入非枚举类型会导致运行时错误。可以通过在辅助函数中添加类型检查来避免这种情况。
  • 性能问题Enum.GetValues方法会创建一个新的数组,对于频繁调用的场景可能会有性能影响。可以考虑缓存枚举值集合。

在C#中如何遍历所有枚举值
https://119291.xyz/posts/how-to-loop-through-all-enum-values-in-csharp/
作者
ww
发布于
2025年5月26日
许可协议