获取枚举的自定义属性的属性

Ray*_*ess 3 c# reflection attributes custom-attributes

我的项目有这个 BookDetails 属性:

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

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

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

}
Run Code Online (Sandbox Code Playgroud)

以及此处的属性代码:

[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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如何获取给定书籍的作者?

尝试了这个混乱的代码,但它不起作用:

 var author = Books.IndianInTheCupboard.GetType().GetCustomAttributes(false).GetType().GetProperty("Author");  // returns null
Run Code Online (Sandbox Code Playgroud)

谢谢,一定有比我上面尝试的更好的方法。

das*_*ght 5

由于该属性附加到enum字段,因此您应该GetCustomAttribute应用于FieldInfo

var res = typeof(Books)
    .GetField(nameof(Books.IndianInTheCupboard))
    .GetCustomAttribute<BookDetails>(false)
    .Author;
Run Code Online (Sandbox Code Playgroud)

由于属性类型是静态已知的,因此应用该方法的通用版本GetCustomAttribute<T>可以产生更好的类型安全性,以获得Author属性带来更好的类型安全性。

演示。