【问题标题】:Convert String to Enum based on enum name根据枚举名称将字符串转换为枚举
【发布时间】:2011-09-20 20:09:55
【问题描述】:

所以我们的枚举设置如下:

[CorrelatedNumeric(0)]
[Description("USD")]
[SequenceNumber(10)]
USD = 247

基本上,另一个函数可以向我提供string“USD”,但不是确切的枚举,因为它的来源是 Excel,我们不能让我们的用户记住枚举值;)也不会产生太大影响感觉。

在 c# 中有没有办法通过设置我们的枚举来从“USD”到 247?

【问题讨论】:

    标签: c# .net enums


    【解决方案1】:

    Enum.TryParse() 或 Enum.Parse() 会满足您的需求吗?

    Currency cValue = (Currency) Enum.Parse(typeof(Currency), currencyString); 
    

    【讨论】:

    • @slandau:这是基于枚举 name,而不是属性值。这就是你所追求的吗?如果是这样,最好更改帖子的标题 - 我的回答是假设您根据 Description 属性想要它。
    • 嗯,实际上它们的名称总是相同的,所以我会更改帖子的标题,但也感谢您的回答:)
    • 请记住,Enum.TryParse“将一个或多个枚举常量的名称或数字值的字符串表示形式转换为等效的枚举对象”。因此,如果您希望用户输入“USD”但他输入“123”,如果您将其中一种货币定义为 123,它可能会通过解析其他货币来传递。
    【解决方案2】:

    绝对 - 通过反射构建 Dictionary<string, YourEnumType>。只需遍历枚举中的所有字段并找到属性值,然后以这种方式构建字典。

    您可以在Unconstrained Melody 中看到我在EnumInternals 中为描述属性做了类似的事情:

    // In the static initializer...
    ValueToDescriptionMap = new Dictionary<T, string>();
    DescriptionToValueMap = new Dictionary<string, T>();
    foreach (T value in Values)
    {
        string description = GetDescription(value);
        ValueToDescriptionMap[value] = description;
        if (description != null && !DescriptionToValueMap.ContainsKey(description))
        {
            DescriptionToValueMap[description] = value;
        }
    }
    
    private static string GetDescription(T value)
    {
        FieldInfo field = typeof(T).GetField(value.ToString());
        return field.GetCustomAttributes(typeof(DescriptionAttribute), false)
                    .Cast<DescriptionAttribute>()
                    .Select(x => x.Description)
                    .FirstOrDefault();
    }
    

    对你自己的属性类型做同样的事情。

    【讨论】:

    • +1,这更有意义,因为它基于描述属性而不是枚举值名称“解析”,就像 Enum.Parse() 那样。
    【解决方案3】:
     public static object enumValueOf(string description, Type enumType)
     {
          string[] names = Enum.GetNames(enumType);
          foreach (string name in names)
          {
              if (descriptionValueOf((Enum)Enum.Parse(enumType, name)).Equals(description))
               {
                   return Enum.Parse(enumType, name);
               }
           }
    
           throw new ArgumentException("The string is not a description of the specified enum.");
      }
    
      public static string descriptionValueOf(Enum value)
      {
           FieldInfo fi = value.GetType().GetField(value.ToString());
           DescriptionAttribute[] attributes = (DescriptionAttribute[]) fi.GetCustomAttributes( typeof(DescriptionAttribute), false);
           if (attributes.Length > 0)
           {
                 return attributes[0].Description;
           }
           else
           {
                return value.ToString();
           }
      }
    

    【讨论】:

      猜你喜欢
      • 2010-10-03
      • 1970-01-01
      • 2012-08-25
      • 2013-08-07
      • 1970-01-01
      • 2014-03-18
      • 2015-06-10
      • 1970-01-01
      相关资源
      最近更新 更多