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

fra*_*ron 24 .net c# casting

我得到以下枚举:

 public enum detallistaDocumentStatus {

    /// <remarks/>
    ORIGINAL,

    /// <remarks/>
    COPY,

    /// <remarks/>
    REEMPLAZA,

    /// <remarks/>
    DELETE,
}
Run Code Online (Sandbox Code Playgroud)

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

 public detallistaDocumentStatus documentStatus {
        get {
            return this.documentStatusField;
        }
        set {
            this.documentStatusField = value;
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

那么,有可能像这样投射吗?

det.documentStatus = (detallistaDocumentStatus)3;
Run Code Online (Sandbox Code Playgroud)

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

ken*_*n2k 48

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

它也可以投射Enum,string反之亦然.

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();
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然不是必需的,但我强烈建议为枚举中的每个成员分配一个int值.如果不这样,则第一个成员为0,第二个成员为1,最多为N.问题是某些环境会对您的枚举进行排序,而其他环境则不会.这将导致不同环境中的不同int值.对我来说,这是我的生产环境排序枚举,而我的localhost没有.这导致了我在开发环境中无法重现的生产错误. (3认同)

Tar*_*ryn 13

对的,这是可能的.我使用以下内容ENUM

public enum AccountTypes
{
  Proposed = 1,
  Open = 2
}
Run Code Online (Sandbox Code Playgroud)

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

(int)AccountTypes.Open
Run Code Online (Sandbox Code Playgroud)

并且它将返回我需要的int值,对于上面的值将为2.

  • OP正试图走另一条路.他有一个整数值,需要找到相应的枚举值. (3认同)

Mic*_*urr 13

来自C#4.0规范:

1.10枚举

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

int i = (int)Color.Blue;      // int i = 2;
Color c = (Color)2;               // Color c = Color.Blue;
Run Code Online (Sandbox Code Playgroud)

另外需要注意的是,允许您在枚举的基础类型范围内(默认情况下为int)转换任何整数值,即使该值未映射到枚举声明中的某个名称.从1.10枚词:

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

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

det.documentStatus = (detallistaDocumentStatus) 42;
Run Code Online (Sandbox Code Playgroud)

即使没有具有该值的枚举名称42.