【问题标题】:Get property of custom attribute for enum获取枚举的自定义属性的属性
【发布时间】:2017-09-12 23:23:04
【问题描述】:

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

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

【问题讨论】:

    标签: c# reflection attributes custom-attributes


    【解决方案1】:

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

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

    由于属性类型是静态已知的,因此应用泛型版本的GetCustomAttribute&lt;T&gt; 方法可以为获取Author 属性提供更好的类型安全性。

    Demo.

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 喜欢扩展方法。
      【解决方案3】:

      已经由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;
      

      【讨论】:

        猜你喜欢
        • 2011-07-03
        • 1970-01-01
        • 2016-07-07
        • 2020-07-19
        • 1970-01-01
        • 1970-01-01
        • 2010-12-20
        相关资源
        最近更新 更多