You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中enum(枚举)使用最佳实践及枚举值转int数组方法

C# 枚举常见问题解答

1. 使用enum创建自定义变量是否属于最佳实践?

这取决于你的使用场景,绝大多数需要标识固定离散选项的场景下,这是公认的最佳实践:

  • 比直接用魔法数字可读性高,代码可维护性更强
  • 自带类型安全,编译阶段就能阻止传入未定义的无效值
  • 不需要额外写校验逻辑判断值是否在合法范围内

只在两种情况下不推荐用枚举:

  • 选项需要动态增减(比如时间段需要支持后台配置新增/删除)
  • 每个选项需要附带多个扩展属性(比如时间段对应的开始结束时间、可预约人数上限等)

2. 针对timeSlots枚举的更优替代方案

如果你的业务仅需要用值标识不同时间段,不需要额外附加信息,这个枚举本身是合理的,只需要调整命名符合C#开发规范即可:枚举类型名用帕斯卡命名法改为TimeSlots,成员也保持帕斯卡命名风格。

如果后续需要给每个时间段附加更多业务属性,可以用*强类型枚举(枚举类)*替代,示例用record实现如下:

public record TimeSlot(int Id, string DisplayName, TimeOnly StartTime, TimeOnly EndTime)
{
    public static readonly TimeSlot Am9h = new(0, "上午9点", new TimeOnly(9,0), new TimeOnly(10,0));
    public static readonly TimeSlot Am10h = new(1, "上午10点", new TimeOnly(10,0), new TimeOnly(11,0));
    // 剩余时间段以此类推定义

    // 提供获取所有选项的方法
    public static IEnumerable<TimeSlot> GetAll() => typeof(TimeSlot)
        .GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)
        .Where(f => f.FieldType == typeof(TimeSlot))
        .Select(f => f.GetValue(null))
        .Cast<TimeSlot>();
}

该方案扩展性更强,适合业务逻辑复杂的场景。


3. 将timeSlots枚举值存入int数组的实现方法

方法1:一行代码直接转换(最推荐,简洁高效)

适用于不需要自定义筛选的场景:

// .NET 5+ 版本支持泛型写法
int[] timeSlotInts = Enum.GetValues<timeSlots>().Cast<int>().ToArray();

// 低版本.NET Framework用非泛型写法
int[] timeSlotInts = Enum.GetValues(typeof(timeSlots)).Cast<int>().ToArray();

方法2:foreach循环实现

适合需要在转换过程中加自定义筛选/处理逻辑的场景:

List<int> intList = new List<int>();
foreach (timeSlots slot in Enum.GetValues(typeof(timeSlots)))
{
    // 此处可添加自定义筛选逻辑,比如只保留下午的时间段
    // if((int)slot >= 4) 
    intList.Add((int)slot);
}
int[] timeSlotInts = intList.ToArray();

方法3:for循环实现

Array slotArray = Enum.GetValues(typeof(timeSlots));
int[] timeSlotInts = new int[slotArray.Length];
for(int i = 0; i < slotArray.Length; i++)
{
    timeSlotInts[i] = (int)slotArray.GetValue(i);
}

三种方法最终得到的数组都是[0,1,2,3,4,5,6,7,8,9],和你定义的枚举值顺序完全一致。


内容的提问来源于stack exchange,提问作者Nixit Ahir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:15:02