2011-09-20 155 views
3

因此,我们有我们的枚举的设置是这样的:字符串转换为枚举的枚举名

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

基本上,另一个功能可提供string“USD”给我,但没有确切的枚举,因为源它是Excel,我们不能让用户记住枚举值;)也不会有多大意义。

有没有办法在c#中从“美元”获得247从我们的枚举设置,因为他们是上面?

回答

13

请问Enum.TryParse()Enum.Parse()做你所需要的?

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

@slandau:这是基于enum * name *而不是属性值。那是你的追求?如果是这样,最好改变你的文章的标题 - 我回答假设你想要它基于'Description'属性。 –

+0

嗯,他们实际上总是命名相同,所以我会改变我的文章的标题,但感谢您的回答以及:) – slandau

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()''做。 –

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