基于索引检索枚举的值 - c#

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

Retrieve value of Enum based on index - c#

c#enums

提问by ltech

This is my enum:

这是我的枚举:

public enum DocumentTypes
    {
        [EnumMember]
        TYPE_1 = 1,
        [EnumMember]
        TYPE_2 = 2,
        [EnumMember]
        TYPE_3 = 3,
        [EnumMember]
        TYPE_4 = 4,
        [EnumMember]
        TYPE_5 = 5,
        [EnumMember]
        TYPE_6 = 6,
        [EnumMember]
        TYPE_7 = 7,
        [EnumMember]
        TYPE_8 = 12

    }

If I want to obtain 'TYPE_8', if I only have 12, is there a way to get the enum value?

如果我想获得'TYPE_8',如果我只有12个,有没有办法获得枚举值?

I tried this:

我试过这个:

((DocumentTypes[])(Enum.GetValues(typeof(DocumentTypes))))[Convert.ToInt32("3")].ToString()

which returns a value of 'TYPE_4'

返回“TYPE_4”的值

采纳答案by PostMan

string str = "";
int value = 12;
if (Enum.IsDefined(typeof (DocumentTypes),value))
     str =  ((DocumentTypes) value).ToString();
else
     str = "Invalid Value";

This gives will also handle invalid values trying to be used, without the internal exception being thrown

这也将处理尝试使用的无效值,而不会引发内部异常

You can also replace the string with DocumentTypes, ie

你也可以用 DocumentTypes 替换字符串,即

DocumentTypes dt = DocumentTypes.Invalid; // Create an invalid enum
if (Enum.IsDefined(typeof (DocumentTypes),value))
   dt = (DocumentTypes) value;

And for the bonus point, here is how to add a custom string to an enum (copied from this SO answer)

对于奖励点,这里是如何将自定义字符串添加到枚举(从这个 SO 答案复制)

Enum DocumentType
{ 
    [Description("My Document Type 1")]
    Type1 = 1,
    etc...
}

Then add an extenstion method somewhere

然后在某处添加一个扩展方法

public static string GetDescription<T>(this object enumerationValue) where T : struct
{
    Type type = enumerationValue.GetType();
    if (!type.IsEnum)
        throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");

    //Tries to find a DescriptionAttribute for a potential friendly name
    //for the enum
    MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
    if (memberInfo != null && memberInfo.Length > 0)
    {
        object[] attrs = memberInfo[0].GetCustomAttributes(typeof (DescriptionAttribute), false);

        if (attrs != null && attrs.Length > 0)
        {
            //Pull out the description value
            return ( (DescriptionAttribute) attrs[0] ).Description;
        }
    }
    //If we have no description attribute, just return the ToString of the enum
    return enumerationValue.ToString();
}

Then you can use:

然后你可以使用:

DocumentType dt = DocumentType.Type1;
string str = dt.GetDescription<DocumentType>();

Which will retrive the Description attribute value.

这将检索描述属性值。



Edit - updated code

编辑 - 更新代码

Here is a new version of the extension method that does't need to know the type of the Enum before hand.

这是一个新版本的扩展方法,不需要事先知道 Enum 的类型。

public static string GetDescription(this Enum value)
{
    var type = value.GetType();

    var memInfo = type.GetMember(value.ToString());

    if (memInfo.Length > 0)
    {
        var attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attrs.Length > 0)
            return ((DescriptionAttribute)attrs[0]).Description;
    }

    return value.ToString();
}

回答by Darin Dimitrov

You can directly cast it:

你可以直接投射它:

int value = 12;
DocumentTypes dt = (DocumentTypes)value;

回答by GraemeF

First of all cast to your enum type and call ToString():

首先转换为您的枚举类型并调用 ToString():

string str = ((DocumentTypes)12).ToString();

回答by t0mm13b

Try this:

尝试这个:

    public enum EnumTest
    {
        EnumOne,
        EnumTwo,
        EnumThree,
        Unknown
    };
    public class EnumTestingClass{
        [STAThread]
        static void Main()
        {
            EnumTest tstEnum = EnumTest.Unknown;
            object objTestEnum;
            objTestEnum = Enum.Parse(tstEnum.GetType(), "EnumThree");
            if (objTestEnum is EnumTest)
            {
                EnumTest newTestEnum = (EnumTest)objTestEnum;
                Console.WriteLine("newTestEnum = {0}", newTestEnum.ToString());
            }
        }
    }

Now from the sample code you will see that newTestEnumwill have the value from the 'EnumTest' equivalent of the string "EnumThree".

现在从示例代码中,您将看到newTestEnum将具有来自与字符串“EnumThree”等价的“EnumTest”的值。

Hope this helps, Best regards, Tom.

希望这会有所帮助,最好的问候,汤姆。

回答by Ata Hoseini

        public enum Projects
    {
        Hotels = 1,
        Homes = 2,
        Hotel_Home = 3
    }


int projectId = rRoom.GetBy(x => x.RoomId == room.RoomId).FirstOrDefault().ProjectId.TryToInt32();
Projects Project = (Projects)projectId;