问题描述
如果我有一个枚举
成员的类,我希望能够重新在那里该成员不定义present的情况下,这岂不是更好?
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)宣布该成员在使用可空类型的类空。例如:
a) Declare the member as nullable in the class using nullable types. E.g.:
public SomeEnum? myEnum;
B)中添加一个默认,未知的价值枚举。例如:
b) Add a default, 'unknown' value to the enumeration. E.g.:
public enum SomeEnum {
Unknown,
SomeValueA,
SomeValueB,
SomeValueC,
}
我实在看不出什么大的优点/缺点无论哪种方式;但也许一个是比其他preferable?
I can't really see any major pros/cons either way; but perhaps one is preferable over the other?
推荐答案
肯定使用可空类型 - 这就是他们的东西。它明确规定你的意图。这也意味着你可以使用<$c$c>Enum.IsDefined$c$c> (或者,如果你想泛型类型安全等效)来轻松地确定特定值是一个的真正的,不用担心假一太值。
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#枚举:可空或“未知”的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!