0

通过其描述属性查找枚举值的可能重复项

我从用户选择的复选框中获得了 MyEnum 的描述,我必须找到该值并保存它。有人可以帮助我如何找到 Enum 给定描述的值

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

例如,我将给 Here is another 我必须返回 N1,当我收到 Last one 时,我必须返回 N3。

我只需要做与如何从值中获取 C# 枚举描述相反的操作?

有人能帮我吗?

4

1 回答 1

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());
于 2012-04-12T15:53:10.317 回答