c# - 有什么办法可以给 c# 枚举一个 "range"的允许值吗?

标签 c# enums

假设我有一个如下所示的枚举,我希望编号从 1000 开始。

public enum Fruits : uint
{
    Apple = 1000,
    Orange = 1001,
    Strawberry = 1002,
    Banana = 1003,
    Blueberry = 1004,
}

为每个 Fruit 分配一个数字是乏味且难以阅读的,更不用说如果我有 20 多个 Fruit 并且可能想重新排序或添加/删除它们时会很尴尬水果。有没有像下面这样的语法?

public enum Fruits : uint where value >= 1000
{
    Apple,
    Orange,
    Strawberry,
    Banana,
    Blueberry,
}

最佳答案

正如@Fabio 在评论中所述,枚举自动值基于前一个枚举的值,因此以下代码片段编译相同:

public enum Fruits : uint
{
    Apple = 1000,
    Orange = 1001,
    Strawberry = 1002,
    Banana = 1003,
    Blueberry = 1004,
}

public enum Fruits : uint
{
    Apple = 1000,
    Orange,
    Strawberry,
    Banana,
    Blueberry,
}

谢谢@Fabio!

关于c# - 有什么办法可以给 c# 枚举一个 "range"的允许值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53439665/

相关文章:

c# - 如何在生产环境中调试 C# Windows 窗体应用程序?

c# - 为什么我的设计器属性没有在 ASPX 中序列化

c# - 使用 C# 在设计器中隐藏调整大小标记?

c# - C#中的TCP监听器启动异常

c# - 获取列表列表中的最大值列表

c# - 枚举到 Int。整数到枚举。转换的最佳方式?

c# - 为什么在将枚举转换为整数失败时我没有得到 InvalidCastException?

python - 为什么定义顺序在 python2 中不可用?

c++ - 无法在枚举中声明 "div"

python - 在 python 和 arduino 之间共享枚举