2017-08-29 84 views
0

這是MyEnumc#如何從自定義屬性獲取枚舉?

public class CountryCodeAttr : EnumAttr 
{ 
    public string Code { get; set; } 
    public string Description { get; set; } 
} 

public enum CountryCode 
{ 
    [CountryCodeAttr(Code = "Unknown", Description = "Unknown")] 
    Unknown, 
    [CountryCodeAttr(Code = "CH", Description = "Swiss", Currency="CHF")] 
    CH 
.... 

} 

我怎樣才能,獲得與特定CountryCodeAttr枚舉?例如從屬性Currency?

+0

我不認爲這是所列出的問題的副本。我相信他在問如何將貨幣值(如「CHF」)解析爲「CountryCode.CH」,類似於https://stackoverflow.com/questions/1033260/how-can-i-get-an-enum-從描述中獲取價值,但具有自定義屬性。 – TylerBrinkley

回答

0

您需要從枚舉類型得到它:

CountryCode value = CountryCode.CH; 
FieldInfo field = typeof(CountryCode).GetField(value.ToString()); 
var attr = field.GetCustomAttribute<CountryCodeAttr>(); 
0

有泛型做到這一點的另一種方法:

public static T GetAttribute<T>(Enum enumValue) where T: Attribute 
{ 
    T attribute; 

    MemberInfo memberInfo = enumValue.GetType().GetMember(enumValue.ToString()) 
            .FirstOrDefault(); 

    if (memberInfo != null) 
    { 
     attribute = (T) memberInfo.GetCustomAttributes(typeof (T), false).FirstOrDefault(); 
     return attribute; 
    } 
    return null; 
}