利弊明确设置枚举字段的值 [英] Pros and Cons explicitly setting enum field's values

查看:64
本文介绍了利弊明确设置枚举字段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否最好显式设置枚举的字段而不是仅定义它们的名称?例如.Enum1 vs Enum2有什么利弊吗?

Is it preferable to explicitly set enum's fields instead of just defining their names? E.g. any pros and cons for Enum1 vs Enum2?

枚举1:

enum SomeEnum
{
   Something1 = 0,
   Something2 = 1
}

枚举2:

enum SomeEnum
{
   Something1,
   Something2
}

P.S.这个问题与将存储在数据库中的枚举无关,这需要显式设置值.

P.S. This question doesn't relates to enums that would be stored in database, which is requires to set values explicitly.

假设所有值均为0、1等...它们不是负数或其他任何值.

Say all values are 0, 1, etc... They are not negative or something.

推荐答案

Enum1和Enum2编译为相同的枚举.因此,从编程的角度来看,没有区别.从维护的角度来看,可能会出现问题,也可能不会出现问题.

Enum1 and Enum2 compile to the same enumeration. So from a programming standpoint, there is no difference. From a maintenance standpoint, there may or may not be issues.

一方面,对于 [Flags] 枚举,绝对需要声明显式值;并且它们必须是2的幂的值.

On the one hand, declaring explicit values is absolutely required for a [Flags] enum; and they need to be values at powers of 2.

另一方面,显式值可以简单地通过创建将来无法更改或不应该更改的值来降低可维护性.

On the other hand, explicit values can reduce maintainability simply by creating values that cannot or should not be changed in the future.

通常,我宁愿不声明显式值,除非值本身由于某些原因而有意义-例如,如果您的C#枚举是包装C枚举.

In general, I prefer to not declare explicit values unless the values themselves are significant for some reason -- if your C# enumeration is, for example, wrapping a C enumeration.

这篇关于利弊明确设置枚举字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆