C#中:如果一个枚举的默认值是无或未知? [英] C#: Should the default value of an enum be None or Unknown?
问题描述
假设你有一个代表错误代码的枚举。会有几个码,每个都有自己的基本int值;然而,得到默认值0枚举值似乎应该慎重考虑。
Say you have an enum that represents an error code. There will be several codes, each with their own underlying int value; however, the enum value that gets the default 0 value seems like it should be carefully considered.
在一个错误代码枚举的情况下,有两个特殊值,我能想到的:无(对于情况下,当没有错误)和未知(对于情况下,当没有现有的错误代码是适当的,或者即使当不能检测错误状态)
In the case of an error code enum, there are two special values that I can think of: None (for cases when there is no error) and Unknown (for cases when no existing error code is appropriate, or perhaps even when error state cannot be detected).
其中的一个值似乎应该得到0,其中其他可能会得到其他的东西像-1。它是更适合于无值设置为0,或未知的值设置为0?
One of these values seems like it should get 0, where the other will probably get something else like -1. Is it more appropriate to set the None value to 0, or the Unknown value to 0?
public enum ErrorCode
{
None = -1,
Unknown = 0,
InsufficientPermissions,
ConnectivityError,
...
}
public enum ErrorCode
{
Unknown = -1,
None = 0,
InsufficientPermissions,
ConnectivityError,
...
}
我的直觉告诉我,默认的应该是未知的,但我很好奇,如果任何人有不同的做到了
My instinct tells me that the default should be Unknown, but I'm curious if anyone has done it differently.
推荐答案
绝对不是一个好的做法。但是,如果没有其他办法...那么我会一般由第二个选项去:
Definitely not a good practice. But if there is no other way...then I would generally go by the second option:
public enum ErrorCode
{
Unknown = -1,
None = 0,
InsufficientPermissions,
ConnectivityError,
...
}
由公约没有错误和-1顺利进入细跟,有一些错误(这可能是未知的理解)。
0 goes well by the convention 'No Error' and -1 goes fine with the understanding that there is some error (which may be unknown).
这篇关于C#中:如果一个枚举的默认值是无或未知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!