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

Get property of custom attribute for enum

我的项目有这个 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

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

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

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

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

Demo.

已由 answered Bryan Rowe 提供。根据您的示例复制他的解决方案:

    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;

您的解决方案不起作用,因为您试图查找 Books 类型的属性,而不是枚举元素的属性。 有效。

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

如果您需要经常获取此属性的值,您可以为其编写扩展。

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