是否可以将整数转换为枚举? [英] Is it possible to cast integer to enum?

查看:20
本文介绍了是否可以将整数转换为枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了以下枚举:

 public enum detallistaDocumentStatus {

    /// <remarks/>
    ORIGINAL,

    /// <remarks/>
    COPY,

    /// <remarks/>
    REEMPLAZA,

    /// <remarks/>
    DELETE,
}

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

then I got a class property of type detallistaDocumentStatus:

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

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

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.

那么,可以这样投射吗?

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

推荐答案

是的,可以将 Enum 转换为 int,反之亦然,因为每个 Enum 实际上默认由 int 表示.您应该手动指定成员值.默认从 0 到 N.

Yes, it's possible to cast Enum to int and vice versa, because every Enum is actually represented by an int per default. You should manually specify member values. By default it starts from 0 to N.

也可以将 Enum 转换为 string,反之亦然.

It's also possible to cast Enum to string and vice versa.

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

这篇关于是否可以将整数转换为枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆