2017-09-12 7 views
1

Mon projet a cette BookDetails attribut:Obtenir propriété d'attribut personnalisé pour ENUM

public enum Books 
{ 
    [BookDetails("Jack London", 1906)] 
    WhiteFange, 

    [BookDetails("Herman Melville", 1851)] 
    MobyDick, 

    [BookDetails("Lynne Reid Banks", 1980)] 
    IndianInTheCupboard 

} 

et le code pour l'attribut ici:

[AttributeUsage(AttributeTargets.Field)] 
public class BookDetails : Attribute 
{ 
    public string Author { get; } 
    public int YearPublished { get; } 

    public BookDetails(string author, int yearPublished) 
    { 
     Author = author; 
     YearPublished = yearPublished; 
    } 
} 

Comment puis-je obtenir l'auteur pour un livre donné?

Essayé ce code compliqué, mais cela n'a pas fonctionné:

var author = Books.IndianInTheCupboard.GetType().GetCustomAttributes(false).GetType().GetProperty("Author"); // returns null 

Merci, il faut que ce soit une meilleure façon que ce que je tentais ci-dessus.

Répondre

2

Puisque l'attribut est attaché à un champ enum, vous devez appliquer GetCustomAttribute à FieldInfo:

var res = typeof(Books) 
    .GetField(nameof(Books.IndianInTheCupboard)) 
    .GetCustomAttribute<BookDetails>(false) 
    .Author; 

Comme type d'attribut est connu statiquement, l'application de la version générique de la méthode GetCustomAttribute<T> rendements une meilleure sécurité de type pour obtenir la Author attribut.

Demo.

0

Déjà par Bryan Rowe answered. La réplication de sa solution accorde votre exemple:

var type = typeof(Books); 
    var memInfo = type.GetMember(Books.IndianInTheCupboard.ToString()); 
    var attributes = memInfo[0].GetCustomAttributes(typeof(BookDetails), false); 
    var description = ((BookDetails)attributes[0]).Author; 
1

Votre solution ne fonctionne pas parce que vous essayez de trouver l'attribut de type livres, mais pas l'attribut de l'élément d'énumération. Cela fonctionne.

var fieldInfo = typeof(Books).GetField(Books.IndianInTheCupboard.ToString()); 
var attribute = fieldInfo.GetCustomAttributes(typeof(BookDetails), false).FirstOrDefault() as BookDetails; 
var author = attribute.Author; 

Si vous avez besoin d'obtenir souvent les valeurs de cet attribut, vous pouvez lui écrire une extension.

public static class EnumExtensions 
{ 
    public static BookDetails GetDescription(this Books value) 
    { 
     var fieldInfo = value.GetType().GetField(value.ToString()); 
     var attribute = fieldInfo.GetCustomAttributes(typeof(BookDetails), false).FirstOrDefault() as BookDetails; 

     return attribute; 
    } 
} 
+0

Aime la méthode d'extension. – RayLoveless