2012-03-26 57 views

回答

0

您可以使用Enum類的Enum.ParseEnum.TryParse方法。

樣品:

CountryCodeEnum value = (CountryCodeEnum)Enum.Parse(SomeEnumStringValue); 
+0

'Enum.Parse'不關注枚舉的屬性。如果你給它「AL」而不是阿拉巴馬州(如OP所示),它不會解析它。 – vcsjones 2012-03-26 15:08:47

0

如果您將得到價值AL,並且要找到具有該屬性的枚舉值,你可以使用反射的一點點明白這一點。

比方說,我們的枚舉看起來是這樣的:

public enum Foo 
{ 
    [Display(Name = "Alabama", ShortName = "AL")] 
    Alabama = 1, 
} 

這裏是一個小的代碼來獲得具有SHORTNAME =「AL」的屬性Foo

var shortName = "AL"; //Or whatever 
var fields = typeof (Foo).GetFields(BindingFlags.Static | BindingFlags.Public); 
var values = from f 
       in fields 
      let attribute = Attribute.GetCustomAttribute(f, typeof (DisplayAttribute)) as DisplayAttribute 
      where attribute != null && attribute.ShortName == shortName 
      select f.GetValue(null); 
    //Todo: Check that "values" is not empty (wasn't found) 
    Foo value = (Foo)values.First(); 
    //value will be Foo.Alabama. 
0

承蒙幫助已經給出的答案和一些額外的研究,我想分享我的解決方案作爲擴展方法,希望它可以幫助其他人:

public static void GetValueByShortName<T>(this Enum e, string shortName, T defaultValue, out T returnValue) 
{ 
    returnValue = defaultValue; 

    var values = from f in typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public) 
       let attribute = Attribute.GetCustomAttribute(f, typeof(DisplayAttribute)) as DisplayAttribute 
       where attribute != null && attribute.ShortName == shortName 
       select (T)f.GetValue(null); 

    if (values.Count() > 0) 
    { 
     returnValue = (T)(object)values.FirstOrDefault(); 
    } 
} 

你可以使用這個擴展爲這樣:

var type = MyEnum.Invalid; 
type.GetValueByShortName(shortNameToFind, type, out type); 
return type; 
0

@jasel我修改您的代碼一點點。這恰好適合我需要的東西。

public static T GetValueByShortName<T>(this string shortName) 
    { 
     var values = from f in typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public) 
        let attribute = Attribute.GetCustomAttribute(f, typeof(DisplayAttribute)) as DisplayAttribute 
        where attribute != null && attribute.ShortName == shortName 
        select (T)f.GetValue(null); 

     if (values.Count() > 0) 
     { 
      return (T)(object)values.FirstOrDefault(); 
     } 

     return default(T); 
    }