应该枚​​举开始与0或1?

2023-09-02 01:52:24 作者:浪荡王者

想我已经定义了以下枚举:

 公共枚举状态:字节
{
    无效= 1,
    活动= 2,
}
 

什么是用枚举的最佳做法是什么?如果用 1 开始像上面的例子,或以 0 (不明确值)是这样的:

 公共枚举状态:字节
{
    不活动,
    活性
}
 

解决方案

框架设计准则:

     

不要提供的非标记零值枚举   如果无不适用于枚举,然后分配零值的元件,该元件   应当用作枚举的默认值。

  

不要使用标志枚举值正常成员为负数或   零。 ..零枚举值产生问题的和的   操作等

  

Imagine I have defined the following Enum:

public enum Status : byte
{
    Inactive = 1,
    Active = 2,
}

What's the best practice to use enum? Should it start with 1 like the above example or start with 0 (without the explicit values) like this:

public enum Status : byte
{
    Inactive,
    Active
}

解决方案

Framework Design Guidelines:

Do provide a value of zero on your non-flags enum If None is not appropriate for the enum, then assign the zero-value to the element which should be used as the default value for the enum.

Avoid using flag enum values normal members that are negative or zero. .. An enum value of zero creates problems with and operations, etc

相关推荐