mardi 12 septembre 2017

C# Get property of custom attribute

My project has this BookDetails attribute:

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

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

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

}

and code for attribute here:

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

How do I get the author for a given Book?

Tried this messy code but it didn't work:

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

Thanks, there's got to be a better way than what I was trying above.





Aucun commentaire:

Enregistrer un commentaire