2017-08-29 3 views
0

Ceci est MyEnumC# Comment obtenir enum à partir de l'attribut personnalisé?

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 
.... 

} 

Comment puis-je, obtenir le ENUM avec un CountryCodeAttr spécifique? par exemple à partir de l'attribut Devise?

+0

Je ne pense pas que ce soit un double de la question figurant. Je crois qu'il demande comment analyser une valeur de devise telle que "CHF" à "CountryCode.CH" qui est similaire à https://stackoverflow.com/questions/1033260/how-can-i-get-an-enum- value-from-its-description mais avec un attribut personnalisé. – TylerBrinkley

Répondre

0

Vous devez obtenir du type ENUM:

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

Il y a une autre méthode pour le faire avec les médicaments génériques:

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