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

时间:2017-09-12 23:23:05

标签: 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

}

以及此处的属性代码:

[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

谢谢,必须有比我上面尝试的更好的方式。

3 个答案:

答案 0 :(得分:2)

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

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

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

Demo.

答案 1 :(得分:1)

您的解决方案不起作用,因为您尝试查找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;
    }
}

答案 2 :(得分:0)

已经由answered布莱恩罗。复制他的解决方案符合你的例子:

    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;