枚举的初始值

发布于 2024-07-29 00:16:51 字数 510 浏览 1 评论 0原文

我有一个类,其属性是枚举枚举

/// <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
  }

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

小红帽 2024-08-05 00:16:51

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

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

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

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

梦途 2024-08-05 00:16:51

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

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

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.

public class MyClass
{
   public EnumDeliveryAction? DeliveryAction { get; set;}
}
紫﹏色ふ单纯 2024-08-05 00:16:51

枚举字段初始化为零; 如果您未在枚举中指定值,它们将从零开始(Email = 0SharePoint=1 等)。

因此,默认情况下,您自己初始化的任何字段都将是 Email。 对于这种情况,添加 None=0 是相对常见的,或者使用 Nullable; 即

/// <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
}

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

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

这应该是:

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

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).

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

/// <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 expected value as a default; i.e.

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);
}
篱下浅笙歌 2024-08-05 00:16:51

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

因此,在您的情况下,您可能会:

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
  }

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

public enum DeliveryAction;

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:

public enum DeliveryAction;
柠檬 2024-08-05 00:16:51

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

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

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

(稍后)

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

输出 - 0


一些回答者提倡使用 Nullable 以满足您的初始化期望。 请注意此建议,因为 Nullable 仍然是值类型,并且具有与引用类型不同的语义。 例如,它永远不会生成空引用异常(它不是引用)。

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");
}

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

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

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

(later)

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

Outputs - 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).

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");
}
勿忘心安 2024-08-05 00:16:51

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

根据 .Net Framework 设计指南,当有意义时,我通常将第一个 Enum 声明为 None (= 0)。

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.

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

得不到的就毁灭 2024-08-05 00:16:51

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

EnumDeliveryAction? action=null;

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;
晨曦慕雪 2024-08-05 00:16:51

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

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.

剪不断理还乱 2024-08-05 00:16:51

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

enum MyEnum
{
    ValueOne,
    ValueTwo
}

在你的班级里

MyEnum? myvariable = null;

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).

enum MyEnum
{
    ValueOne,
    ValueTwo
}

and in your class

MyEnum? myvariable = null;
稍尽春風 2024-08-05 00:16:51

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

typedef static const int enum;

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

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

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

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...).

Anyway, the default value of any int is 0.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文