【问题标题】:How to get Enum Value By Description [duplicate]如何通过描述获取枚举值[重复]
【发布时间】:2015-05-13 08:03:01
【问题描述】:
public enum States
{
        [Description("New Hampshire")]
        NewHampshire = 29,
        [Description("New York")]
        NewYork = 32,
}

这里我必须通过描述来获取数据 例子: 我需要新罕布什尔州的 29 动态不使用索引位置

【问题讨论】:

  • 你试过什么?
  • 抱歉没试过

标签: c# enums


【解决方案1】:

您可以将您的字符串传递给 GetDataByDescription 方法。我已将 Aydin Adn 的答案用于 GetAttribute 方法。

internal class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine(GetDataByDescription("New Hampshire"));
    }

    private static int GetDataByDescription(string s)
    {
        foreach (States state in Enum.GetValues(typeof (States)))
        {
            if (GetAttribute<DescriptionAttribute>(state).Description == s)
            {
                return (int) state;
            }
        }

        throw new ArgumentException("no such state");
    }

    private static TAttribute GetAttribute<TAttribute>(Enum enumValue)
        where TAttribute : Attribute
    {
        return enumValue.GetType()
            .GetMember(enumValue.ToString())
            .First()
            .GetCustomAttribute<TAttribute>();
    }
}

【讨论】:

    【解决方案2】:

    你可以这样做:

    States s;
    var type = typeof(States);
    foreach (var field in type.GetFields())
    {
        var attribute = Attribute.GetCustomAttribute(field,
            typeof(DescriptionAttribute)) as DescriptionAttribute;
        if (attribute != null)
        {
            if (attribute.Description == "description")
            {
                s = (States)field.GetValue(null);
                break;
            }
        }
        else
        {
            if (field.Name == "description")
            {
                s = (Rule)field.GetValue(null);
                break;
            }
        }
    } 
    

    【讨论】:

      【解决方案3】:

      这是一个通用方法,您可以使用任何属性

      public static class Extensions
      {
          public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) 
                  where TAttribute : Attribute
          {
              return enumValue.GetType()
                              .GetMember(enumValue.ToString())
                              .First()
                              .GetCustomAttribute<TAttribute>();
          }
      }
      

      这将帮助您实现您的目标......

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-28
        • 1970-01-01
        • 2011-05-21
        • 2011-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-19
        相关资源
        最近更新 更多