【问题标题】:How do I retrieve attributes on properties in C#?如何在 C# 中检索属性的属性?
【发布时间】:2011-08-03 06:16:44
【问题描述】:

我正在尝试实现一个简单的 API,用户可以在其中使用属性属性来指定对象属性的排序。

类似:

[Sorting(SortOrder=0)]
public string Id { get; set; }

在基本的 ToString() 方法中,然后我使用反射从对象中提取属性。

Type currentType = this.GetType();
PropertyInfo[] propertyInfoArray = currentType.GetProperties(BindingFlags.Public);
Array.Sort(propertyInfoArray, this.comparer);

我已经使用 IComparer 接口编写了一个自定义类来执行 Array.Sort,但是一旦我进入其中,我就会在尝试检索 [Sorting] 属性时遇到困难。我目前有这样的东西:

PropertyInfo xInfo = (PropertyInfo)x;
PropertyInfo yInfo = (PropertyInfo)y;

我以为我可以使用 xInfo.Attributes,但 PropertyAttributes 类并没有做我需要它做的事情。有人对如何检索该 [排序] 属性有任何指导吗?我环顾四周,但由于“属性”一词在编程中的重载,我不断得到很多错误的线索和死胡同。

【问题讨论】:

    标签: c# reflection attributes properties


    【解决方案1】:

    使用MemberInfo.GetCustomAttributes

    System.Reflection.MemberInfo info = typeof(Student).GetMembers()
                                                       .First(p => p.Name== "Id");
    object[] attributes = info.GetCustomAttributes(true);
    

    编辑:

    要获取值本身,请查看this answer

    祝你好运!

    【讨论】:

      【解决方案2】:

      试试这个:

      System.Reflection.MemberInfo info = typeof(MyClass);
      object[] attributes = info.GetCustomAttributes(true);
      

      【讨论】:

      • 这会检索类上的任何自定义属性,而不是属性上的 SortingAttribute。
      • 没错,虽然想法相同...propertyInfo.GetCustomAttributes(boolean);
      【解决方案3】:

      我一般为此使用一组扩展方法:

      public TAttribute GetAttribute<TAttribute>(this ICustomAttributeProvider provider, bool inherit = false)
        where TAttribute : Attribute
      {
        return GetAttributes<TAttribute>(provider, inherit).FirstOrDefault();
      }
      
      public IEnumerable<TAttribute> GetAttributes<TAttribute>(this ICustomAttributeProvider provider, bool inherit = false)
        where TAttribute : Attribute
      {
        return provider.GetCustomAttributes(typeof(TAttribute), inherit).Cast<TAttribute>()
      }
      

      我可以这样称呼它:

      var attrib = prop.GetAttribute<SortingAttribute>(false);
      

      不过,从设计的角度来看,我会确保您只检查这些属性,因为反射并不总是很快。如果您要比较多个对象,您可能会发现使用反射有点瓶颈。

      【讨论】:

        【解决方案4】:

        GetCustomAttributes 是您要使用的方法。

        SortingAttribute[] xAttributes = (SortingAttribute[])xInfo.GetCustomAttributes(typeof(SortingAttribute), true);
        

        【讨论】:

          【解决方案5】:

          您需要使用GetCustomAttributes 方法。

          【讨论】:

            【解决方案6】:

            您应该能够在 PropertyInfo 实例上使用 MemberInfo.GetCustomAttributes 获取属性。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2011-06-07
              • 2023-03-10
              • 1970-01-01
              • 2019-12-06
              • 1970-01-01
              • 2012-09-13
              相关资源
              最近更新 更多