C# 是否可以将整数转换为枚举?

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

Is it possible to cast integer to enum?

c#.netcasting

提问by franko_camron

I got the following enum:

我得到了以下枚举:

 public enum detallistaDocumentStatus {

    /// <remarks/>
    ORIGINAL,

    /// <remarks/>
    COPY,

    /// <remarks/>
    REEMPLAZA,

    /// <remarks/>
    DELETE,
}

then I got a class property of type detallistaDocumentStatus:

然后我得到了一个 detallistaDocumentStatus 类型的类属性:

 public detallistaDocumentStatus documentStatus {
        get {
            return this.documentStatusField;
        }
        set {
            this.documentStatusField = value;
        }
    }

In the real life the user will send us a number (1, 2, 3 or 4) representing each enum value in the order they are declared.

在现实生活中,用户会按照声明的顺序向我们发送一个数字(1、2、3 或 4)来表示每个枚举值。

so, is it possible to cast like this?

那么,可以这样投射吗?

det.documentStatus = (detallistaDocumentStatus)3;

if not, how could I get the enum value using an integer as an index, we are using a lot of enums, so we want to do something generic and reusable

如果没有,我怎么能使用整数作为索引来获取枚举值,我们使用了很多枚举,所以我们想做一些通用和可重用的事情

采纳答案by ken2k

Yes, it's possible to cast Enumto intand vice versa, because every Enumis actually represented by an intper default. You should manually specify member values. By default it starts from 0 to N.

是的,可以强制转换Enumint,反之亦然,因为每个Enum实际上都由int每个默认值表示。您应该手动指定成员值。默认情况下,它从 0 到 N 开始。

It's also possible to cast Enumto stringand vice versa.

也可以强制转换Enumstring,反之亦然。

public enum MyEnum
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 3
}

private static void Main(string[] args)
{
    int enumAsInt = (int)MyEnum.Value2; //enumAsInt == 2

    int myValueToCast = 3;
    string myValueAsString = "Value1";
    MyEnum myValueAsEnum = (MyEnum)myValueToCast;   // Will be Value3

    MyEnum myValueAsEnumFromString;
    if (Enum.TryParse<MyEnum>(myValueAsString, out myValueAsEnumFromString))
    {
        // Put logic here
        // myValueAsEnumFromString will be Value1
    }

    Console.ReadLine();
}

回答by Taryn

Yes it is possible. I use the following ENUM

对的,这是可能的。我使用以下ENUM

public enum AccountTypes
{
  Proposed = 1,
  Open = 2
}

then when I call it I use this to get the value:

然后当我调用它时,我使用它来获取值:

(int)AccountTypes.Open

And it will return the int value that I need which for the above will be 2.

它将返回我需要的 int 值,上面将是 2。

回答by Leon

ENUMs are just a convenient way to name integers. Values of an ENUM can be added, subtracted and compared the same way an intcan be.

ENUM 只是命名整数的一种便捷方式。ENUM 的值可以以相同的方式添加、减去和比较int

回答by IUnknown

det.documentStatus = (detallistaDocumentStatus)3;

The above should work fine. Only thing to remember here is if you are assigning specific numbers to enum members then something like this may not work as expected. Also if you are not explicitly numbering your enum values then the enum members start at zero based index.

以上应该可以正常工作。这里唯一要记住的是,如果您为枚举成员分配特定数字,那么这样的事情可能无法按预期工作。此外,如果您没有明确编号枚举值,则枚举成员从基于零的索引开始。

So the above code would assign 4th member of the enum in the order of declaration.

所以上面的代码将按照声明的顺序分配枚举的第 4 个成员。

To check whether a given integer is a valid enum value for that enum use Enum.IsDefined

要检查给定的整数是否是该枚举的有效枚举值,请使用Enum.IsDefined

回答by 3Dave

If you give an explicit integer value for your enum members, like so:

如果您为枚举成员提供显式整数值,如下所示:

public enum Foo
{
    Five=5
    , Six
    , Seven
    , Eight
}

You can just cast them to an intto get the implicit value.

您可以将它们强制转换为 anint以获取隐式值。

var bar = (int)Foo.Six: /// bar == 6

If you don't explicitly define a value for at least the first, casting it to an int will give you the order in which it appears in the declaration.

如果您没有明确定义至少第一个值,则将其转换为 int 将为您提供它在声明中出现的顺序。

回答by Michael Burr

From the C# 4.0 Specification:

来自 C# 4.0 规范:

1.10 Enums

Enum values can be converted to integral values and vice versa using type casts. For example

int i = (int)Color.Blue;      // int i = 2;
Color c = (Color)2;               // Color c = Color.Blue;

1.10 枚举

可以使用类型转换将枚举值转换为整数值,反之亦然。例如

int i = (int)Color.Blue;      // int i = 2;
Color c = (Color)2;               // Color c = Color.Blue;

One additional thing to be aware of is that you are permitted to cast any integral value in the range of the enum's underlying type (by default that's int), even if that value doesn't map to one of the names in the enum declaration. From 1.10 Enums:

需要注意的另一件事是,您可以强制转换枚举基础类型范围内的任何整数值(默认情况下为 int),即使该值未映射到枚举声明中的名称之一。从 1.10 枚举:

The set of values that an enum type can take on is not limited by its enum members. In particular, any value of the underlying type of an enum can be cast to the enum type and is a distinct valid value of that enum type.

枚举类型可以采用的值集不受其枚举成员的限制。特别是,枚举的基础类型的任何值都可以转换为枚举类型,并且是该枚举类型的不同有效值。

So, the following is also permitted with the enum in your example:

因此,您的示例中的枚举也允许以下内容:

det.documentStatus = (detallistaDocumentStatus) 42;

even though there's no enum name that has the value 42.

即使没有具有 value 的枚举名称42