【问题标题】:How are the default values for numeric types chosen (when no identifiers are given) by the enum in C#? [duplicate]C# 中的枚举如何选择数字类型的默认值(当没有给出标识符时)? [复制]
【发布时间】:2021-10-17 14:21:34
【问题描述】:

当我使用代码时:

enum Programs {BSE, BCS, BSDS}

选择默认值“BSE”,但用于:

enum Year: ushort {year1=2021, year2=2022}

代码没有给出默认年份 2021。 我该如何解决这个问题?有没有办法在枚举中选择 numeric 类型?

【问题讨论】:

  • enum 的默认值始终为0,因为它是一个整数。多年来使用enum 似乎有点坏主意
  • 请注意,Year y = (Year) 1984 是完全合法的,并且看起来并非不合理。将“2021”设置为“基准年”可以在没有枚举的情况下完成,如果需要强制执行,可能应该在没有枚举的情况下完成。

标签: c# enums


【解决方案1】:

在此处查看文档:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum

枚举类型E的默认值是表达式(E)0产生的值,即使零没有对应的枚举成员

这里有另一个流行的答案Choosing the default value of an Enum type without having to change values 使用属性,但这不会改变未分配枚举类型的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    • 2016-04-16
    • 2021-07-21
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    相关资源
    最近更新 更多