检索枚举的值,给出枚举的描述

时间:2012-04-12 15:35:45

标签: c# enums

Finding an enum value by its Description Attribute

可能重复

我从用户选中的复选框中获取MyEnum的描述, 我必须找到值并保存它。有人可以帮我找到Enum给出描述的价值

public enum MyEnum
{
   [Description("First One")]
   N1,
   [Description("Here is another")]
   N2,
   [Description("Last one")]
   N3
}

例如我将被给予这是另一个我必须返回N1,当我收到最后一个我必须返回N3。

我必须做与How to get C# Enum description from value?

相反的事情

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

像这样:

// 1. define a method to retrieve the enum description
public static string ToEnumDescription(this Enum value)
{
    FieldInfo fi = value.GetType().GetField(value.ToString());

    DescriptionAttribute[] attributes =
        (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute),
        false);

    if (attributes != null &&
        attributes.Length > 0)
        return attributes[0].Description;
    else
        return value.ToString();
}

//2. this is how you would retrieve the enum based on the description:
public static MyEnum GetMyEnumFromDescription(string description)
{
    var enums = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();

    // let's throw an exception if the description is invalid...
    return enums.First(c => c.ToEnumDescription() == description);
}

//3. test it:
var enumChoice = EnumHelper.GetMyEnumFromDescription("Third");
Console.WriteLine(enumChoice.ToEnumDescription());