根据枚举名称将字符串转换为枚举类型

4
所以我们的枚举类型设置如下:
[CorrelatedNumeric(0)]
[Description("USD")]
[SequenceNumber(10)]
USD = 247

基本上,另一个函数可以向我提供字符串“USD”,但不能提供确切的枚举值,因为它的来源是Excel,我们不能让用户记住枚举值;)也没有太多意义。

在c#中,是否有一种方法可以从上面设置的枚举中获取247的值,而起点是“USD”?

3个回答

16

你需要使用 Enum.TryParse() 或者 Enum.Parse() 吗?

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

1
@slandau:这是基于枚举名称进行的,而不是属性值。这是否符合您的要求?如果是的话,最好更改您的帖子标题——我回答时假设您想要基于“描述”属性。 - Jon Skeet
好的,它们实际上总是被命名为相同的名称,所以我会更改我的帖子标题,但还是谢谢你的回答 :) - slandau
请注意,Enum.TryParse“将一个或多个枚举常量的名称或数字值的字符串表示转换为等效的枚举对象”。因此,如果您希望用户输入“USD”,但他输入了“123”,则在解析定义为123的其他货币时可能会通过。 - broslav

4
完全可以通过反射构建一个 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
+1,这样更有意义,因为它基于描述属性而不是枚举值名称进行“解析”,就像Enum.Parse()一样。 - Philip Daubmeier

1
 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();
       }
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接