我的项目有这个BookDetails属性:
public enum Books
{
[BookDetails("Jack London", 1906)]
WhiteFange,
[BookDetails("Herman Melville", 1851)]
MobyDick,
[BookDetails("Lynne Reid Banks", 1980)]
IndianInTheCupboard
}
并在此处添加属性的代码:
[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;
}
}
如何获取给定书籍的作者?
尝试了这段混乱的代码,但没有起作用:
var author = Books.IndianInTheCupboard.GetType().GetCustomAttributes(false).GetType().GetProperty("Author"); // returns null
谢谢,肯定有比我之前尝试的方法更好的。