【问题标题】:Retrieve value of enum given description of enum [duplicate]根据枚举的描述检索枚举的值[重复]
【发布时间】:2012-04-12 15:35:44
【问题描述】:

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
}

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

我只需要做与How to get C# Enum description from value?相反的事情

有人可以帮我吗?

【问题讨论】:

  • SomeType test = (SomeType )Enum.Parse(typeof(SomeType ), "Three");
  • 比将代码从答案复制到项目中然后使用更简单吗?对我来说听起来很容易。
  • this 更简单吗?

标签: c# enums


【解决方案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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 2015-12-30
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多