C# 枚举:可为空或“未知”值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1795657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:54:15  来源:igfitidea点击:

C# Enums: Nullable or 'Unknown' Value?

c#enums

提问by UpTheCreek

If I have a class with an enummember and I want to be able to represent situations where this member is not defined, which is it better?

如果我有一个带有enum成员的类,并且我希望能够表示未定义该成员的情况,哪个更好?

a) Declare the member as nullable in the class using nullable types. E.g.:

a) 使用可为空类型在类中将该成员声明为可为空的。例如:

public SomeEnum? myEnum;

b) Add a default, 'unknown' value to the enumeration. E.g.:

b) 为枚举添加一个默认的“未知”值。例如:

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?

无论哪种方式,我都看不到任何主要的优点/缺点;但也许一个比另一个更可取?

采纳答案by Jon Skeet

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 Melodyif you want generic type safety) to easily determine whether a particular value is a realvalue without worrying about the "fake" one too.

绝对使用可空值类型 - 这就是它们的用途。它明确说明了您的意图。这也意味着您可以使用Enum.IsDefined(如果您想要泛型类型安全,则可以使用Unconstrained Melody 中的等效项)轻松确定特定值是否为真实值,而不必担心“假”值。

回答by Fiona - myaccessible.website

If it's nullable, you'd get it as a default value, you'd get exceptions if you tried to use it when null (which is a good thing!)

如果它是可空的,你会得到它作为默认值,如果你试图在 null 时使用它,你会得到异常(这是一件好事!)

回答by archimed7592

You just have to decide whether you need a value to represent unknown values, or you do need a way to represent absence of any value.

您只需要决定是否需要一个值来表示未知值,或者您确实需要一种方法来表示没有任何值。

In the case of a need to represent unknown values, an extra enum-member sounds good as a solution.

在需要表示未知值的情况下,额外的枚举成员听起来不错作为解决方案。

In case of a need to represent absence of any value, make it nullable.

如果需要表示没有任何值,请将其设为可空。

Have in mind, that there is nothing wrong with having both "unknown" enum-member and the enum itself being nullable at the same time.

请记住,同时拥有“未知”枚举成员和枚举本身可以为空并没有错。

HTH.

哈。

回答by Maarten jansonius

I agree with archimed7592 that there is a real difference between absent value and "Unknown" value.

我同意 archimed7592 的观点,即缺失值和“未知”值之间存在真正的区别。

Example:

例子:

"what is your blood type?"

“你的血型是什么?”

  • Null = absent value --> question hasn't been answered --> ask the question

  • "Unknown" --> patient indicates he doesn't know --> order lab test for the blood type

  • Null = 缺失值 --> 问题尚未回答 --> 提出问题

  • “未知”--> 患者表示他不知道--> 为血型进行实验室测试

回答by Hamish Grubijan

IT DEPENDS!

这取决于!

Bill Wagner has listed some good reasons to add an Undefinedenumwhen it makes sense. I suggest that you find the full item, but here's a preview:

比尔·瓦格纳 (Bill Wagner) 列出了一些在有意义时添加Undefined 的充分理由enum。我建议你找到完整的项目,但这里有一个预览:

Item 8: Ensure That 0 Is a Valid State for Value Types

The default .NET system initialization sets all objects to all 0s. There is no way for you to prevent other programmers from creating an instance of a value type that is initialized to all 0s. Make that the default value for your type.

One special case is enums. Never create an enum that does not include 0 as a valid choice. All enums are derived from System.ValueType. The values for the enumeration start at 0, but you can modify that behavior...

第 8 项:确保 0 是值类型的有效状态

默认的 .NET 系统初始化将所有对象设置为全 0。您无法阻止其他程序员创建初始化为全 0 的值类型的实例。将其设为您的类型的默认值。

一种特殊情况是枚举。切勿创建不包含 0 作为有效选择的枚举。所有枚举都派生自 System.ValueType。枚举值从 0 开始,但您可以修改该行为...

Now, I have a situation where the users need to select some type from a ComboBox, or they can have no type selected. I am using an enum with a [Description("a description")]attribute as the object to be selected. If none/Unknown is a natural choice for an enum, then I would use that to represent that nothing is selected. Otherwise, I will use a Nullable<MyEnum>.

现在,我遇到一种情况,用户需要从 ComboBox 中选择某种类型,或者他们可以不选择任何类型。我正在使用带有[Description("a description")]属性的枚举作为要选择的对象。如果 none/Unknown 是枚举的自然选择,那么我将使用它来表示没有选择任何内容。否则,我将使用Nullable<MyEnum>.

回答by LuckyLikey

Everything changes if the enum is attributed with [Flags]Attribute.

如果枚举被归因于[Flags]Attribute,一切都会改变。

    [Flags]
    enum FlagsEnum
    {
        None = 0,
        First = 1,
        Second = 2,
        Third = 4,
        FirstAndThird = 5
    }