问题描述
如果我有一个具有枚举
成员的类,并且我想能够表示这个成员没有被定义的情况,哪个更好?
If I have a class with an enum
member and I want to be able to represent situations where this member is not defined, which is it better?
a)使用可空类型在该类中声明成员为空。公开SomeEnum?
a) Declare the member as nullable in the class using nullable types. E.g.:
public SomeEnum? myEnum;
b)为枚举添加一个默认的'unknown'值。例如:
b) Add a default, 'unknown' value to the enumeration. E.g.:
public enum SomeEnum {
Unknown,
SomeValueA,
SomeValueB,
SomeValueC,
}
我无法真正看到任何主要的利弊办法;但是也许比其他人更喜欢一个?
I can't really see any major pros/cons either way; but perhaps one is preferable over the other?
推荐答案
绝对使用一个可空的值类型 - 这就是他们所要做的。它明确表示你的意图。这也意味着您可以使用(或等同于如果您想要通用类型的安全性)轻松确定特定值是否为真实值,而不必担心假。
Definitely use a nullable value type - that's what they're for. It explicitly states your intention. It also means you can use Enum.IsDefined
(or the equivalent from Unconstrained Melody if you want generic type safety) to easily determine whether a particular value is a real value without worrying about the "fake" one too.
这篇关于C#枚举:可空或“未知”值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!