检索给定枚举描述的枚举值

本文关键字:枚举 描述 检索 | 更新日期: 2023-09-27 18:30:49

可能重复 通过枚举属性查找枚举值

我从用户选中的复选框中获取 MyEnum 的描述,我必须找到值并保存它。有人可以帮我如何找到给定描述的枚举的值

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

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

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

有人可以帮助我吗?

检索给定枚举描述的枚举值

像这样:

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