C# 枚举的初始值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1165402/
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 09:46:28  来源:igfitidea点击:

Initial Value of an Enum

c#enums

提问by JL.

I have a class with a property which is an enum

我有一个类的属性是一个枚举

The enum is

枚举是

/// <summary>
/// All available delivery actions
/// </summary>
public enum EnumDeliveryAction
  {
    /// <summary>
    /// Tasks with email delivery action will be emailed
    /// </summary>
    Email,

    /// <summary>
    /// Tasks with SharePoint delivery action 
   /// </summary>
   SharePoint
  }

When I create an instance of this class, NOWHERE in the code, do I specify the value of the enum field, but it seems to default to the first item in the enumlist, and not a null value, is this how enums work? How is it possible to ensure that the enum gets some kind of null value if it is not set, I don't want it defaulting to the first value in the enum.

当我创建此类的实例时,在代码中没有指定枚举字段的值,但它似乎默认为枚举列表中的第一项,而不是空值,这是枚举的工作方式吗?如果未设置,如何确保枚举获得某种空值,我不希望它默认为枚举中的第一个值。

采纳答案by Mehrdad Afshari

Default value for enumtypes is 0(which is by default, the first element in the enumeration). Fields of a class will be initialized to the default value.

enum类型的默认值是0(默认情况下是枚举中的第一个元素)。类的字段将被初始化为默认值。

If you need to represent an unknownvalue in the enum, you can add an element Unknownwith value 0. Alternatively, you could declare the field as Nullable<MyEnum>(MyEnum?).

如果您需要在枚举中表示一个未知值,您可以添加一个Unknown值为 0的元素。或者,您可以将该字段声明为Nullable<MyEnum>( MyEnum?)。

回答by Josh Kodroff

Enums are a value type, like ints. You need to make it nullable so as not to default to the first (or 0-defined) enum member.

枚举是一种值类型,就像整数一样。您需要使其可以为空,以免默认为第一个(或 0 定义的)枚举成员。

public class MyClass
{
   public EnumDeliveryAction? DeliveryAction { get; set;}
}

回答by Marc Gravell

Enum fields are initialized as zero; an if you don't specify values in an enum, they start at zero (Email = 0, SharePoint=1, etc).

枚举字段初始化为零;一,如果你不枚举指定的值,便开始在零(Email = 0SharePoint=1,等)。

Thus by default any field you do initialize yourself will be Email. It is relatively common to add None=0for such cases, or alternatively use Nullable<T>; i.e.

因此,默认情况下,您自己初始化的任何字段都将是Email. None=0在这种情况下添加或使用Nullable<T>; IE

/// <summary>
/// All available delivery actions
/// </summary>
public enum EnumDeliveryAction
{
    /// <summary>
    /// Not specified
    /// </summary>
    None,

    /// <summary>
    /// Tasks with email delivery action will be emailed
    /// </summary>
    Email,

    /// <summary>
    /// Tasks with SharePoint delivery action 
   /// </summary>
   SharePoint
}

You should also be sure to never treat your last expectedvalue as a default; i.e.

您还应该确保永远不要将您的最后一个预期值视为默认值;IE

switch(action) {
    case EnumDeliveryAction.Email; RunEmail(); break;
    default: RunSharePoint(); break;
}

this should be:

这应该是:

switch(action) {
    case EnumDeliveryAction.Email; RunEmail(); break;
    case EnumDeliveryAction.SharePoint; RunSharePoint(); break;
    default: throw new InvalidOperationException(
          "Unexpected action: " + action);
}

回答by Blindy

The traditional aproach to adding a null to values that don't generally have one is to declare your variable as a nullable type, ie:

向通常没有空值的值添加空值的传统方法是将变量声明为可空类型,即:

EnumDeliveryAction? action=null;

回答by BCarter

I'd suggest having a value of None = 0 as your first enum value. Make it explicit, then you know for sure what it's value is.

我建议将 None = 0 的值作为您的第一个枚举值。让它明确,然后你肯定知道它的价值是什么。

回答by Mitch Wheat

You can start your enums at any value (such as 1), but when they represent a lookup value in a Database, you generally want them to match up.

您可以从任何值(例如 1)开始您的枚举,但是当它们代表数据库中的查找值时,您通常希望它们匹配。

I generally declare the first Enum as None ( = 0) when it makes sense to do so, as per the .Net Framework Design guidelines.

根据 .Net Framework Design 指南,我通常将第一个 Enum 声明为 None (= 0)。

回答by Winston Smith

Best practice (as advised by Code Analysis) is to always have a default value in your enums, which represent an unset value.

最佳实践(根据代码分析的建议)是在您的枚举中始终有一个默认值,它代表一个未设置的值。

So in your case, you might have:

所以在你的情况下,你可能有:

public enum EnumDeliveryAction
   {

    /// <summary>
    /// Default value
    /// </summary>
    NotSet,

    /// <summary>
    /// Tasks with email delivery action will be emailed
    /// </summary>
    Email,

    /// <summary>
    /// Tasks with SharePoint delivery action 
   /// </summary>
   SharePoint
  }

As an aside, you shouldn't prefix the name of the enum with Enum. You might consider changing to:

顺便说一句,您不应该在枚举的名称前加上 Enum。您可能会考虑更改为:

public enum DeliveryAction;

回答by monkey_p

By default only reference types are nullable types. If you want a variable to allow nulls you have to define it as nullable using the "?" character (for this you need C# 2.0 or up).

默认情况下,只有引用类型是可空类型。如果您希望变量允许空值,则必须使用“?”将其定义为可空值。字符(为此您需要 C# 2.0 或更高版本)。

enum MyEnum
{
    ValueOne,
    ValueTwo
}

and in your class

在你的课堂上

MyEnum? myvariable = null;

回答by Amy B

Enums are value types. Value types cannot be null and are initialized to 0.

枚举是值类型。值类型不能为 null 并且被初始化为 0。

Even if your enum does not have a 0, enum variables will be initialized to 0.

即使您的枚举没有 0,枚举变量也会被初始化为 0。

public enum SomeEnum
{
    A = 1,
    B = 2
}

(later)

(之后)

SomeEnum x = default(SomeEnum);
Console.WriteLine(x);

Outputs - 0

输出 - 0



Some answerers are advocating using Nullable<T>to match your initialization expectations. Becareful with this advice since Nullable<T>is still a value type and has different semantics than reference types. For example, it will never generate a null reference exception (it's not a reference).

一些回答者提倡使用Nullable<T>来匹配您的初始化期望。小心这个建议,因为Nullable<T>它仍然是一个值类型并且与引用类型具有不同的语义。例如,它永远不会生成空引用异常(它不是引用)。

SomeEnum? x = default(SomeEnum?);

if (x == null)
{
    Console.WriteLine("It's null!");
}
if (x > SomeEnum.B)
{
}
else
{
    Console.WriteLine("This runs even though you don't expect it to");
}

回答by SsJVasto

My C++ teacher in college (11 years ago) told me that the linker replaces enum with their actual type:

我在大学的 C++ 老师(11 年前)告诉我,链接器将 enum 替换为它们的实际类型:

typedef static const int enum;

typedef static const int enum;

Thus, any time you write something like enum MY_VAL = 5;, you could easily replace with static const int MY_VAL = 5;(but that just makes your code longer...).

因此,任何时候您编写类似 的东西时enum MY_VAL = 5;,您都可以轻松地替换为static const int MY_VAL = 5;(但这只会使您的代码变得更长......)。

Anyway, the default value of any intis 0.

无论如何,any 的默认值int是 0。