使用 EnumType.None 还是 Nullable?
枚举通常用于定义类的特定属性的状态,例如在某种对象模型中。对于其中一些属性,“此属性未设置”状态是有效的。
在这些情况下,我应该使用零 None
枚举值,还是使属性类型可为空?
public MyEnum Property { get; set; }
public enum MyEnum {
None = 0,
Value1,
Value2
}
或者
public MyEnum? Property { get; set; }
public enum MyEnum {
Value1,
Value2
}
Enums are generally used to define the state of a particular property of a class, say in an object model of some sort. For some of these properties, the state 'this property is not set' is valid.
In these situations, should I use a zero None
enum value, or make the property type nullable?
public MyEnum Property { get; set; }
public enum MyEnum {
None = 0,
Value1,
Value2
}
or
public MyEnum? Property { get; set; }
public enum MyEnum {
Value1,
Value2
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
MyEnum.None
- 它更具表现力,甚至可以使用MyEnum.Invalid
来传达含义。您还可以将其设置为 0 以外的其他值 - 因为它基于 int,您可以将其设置为 -1,并将第一个有效值设置为 1:
在您的代码中,您可以轻松检查传入的该值并抛出描述性异常。
可以为 null 的枚举类型不是预期的并且表达能力较差。它要求代码的用户意识到这一点并检查空值。
Use
MyEnum.None
- it is much more expressive, or evenMyEnum.Invalid
to convey meaning.You can also set it to other values than 0 - since it is based on int, you can set it to be -1 and the first valid value to 1:
In your code you can easily check for this value being passed in and throw a descriptive exception.
A nullable enum type is not expected and less expressive. It requires users of you code to be aware of this and check for nulls.
很难得出结论性的答案,应用程序中的很多因素都会影响这一点。我倾向于将枚举值定义为 0,但不在枚举中指定零值。
这提供了哨兵值的好处,而不会污染枚举。
It's hard to answer this conclusively, a lot of factors in your app will influence this. I tend to just define the enum value to 0, but not specify a zero value in the enum.
This gives the benefit of a sentinel value, without polluting the enum.
我会使用“None”值而不是可为空的枚举。如果不出意外的话,对我来说
if(Property == MyEnum.None)
比if(Property == null)
更具可读性。I would use the "None" value instead of a nullable enum. If nothing else, to me
if(Property == MyEnum.None)
is a lot more readable thanif(Property == null)
.另一种选择是将第一个值设置为 1,因为它最初为 0。
我认为你的两种情况都是可以接受的!这将取决于您的情况。使用用户界面时,带有“None”值的第一个示例可能会更易于使用。但是,Nullable 提供了有关如何使用变量的更多信息。
Another option is to set the first value to 1, since it will be initally 0.
I think both of your situations are acceptable! It will depend upon your situation. When working with a user interface your first example with the 'None' value will probbaly be easier to use. However, the Nullable gives more information about how the variable should be used.