如何在C#中检索属性的属性?

时间:2011-04-11 17:25:39

标签: c# reflection attributes properties

我正在尝试实现一个简单的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类没有按照我的需要去做。有没有人对如何检索[Sorting]属性有任何指导?我已经四处寻找了很多,但是在编程中,属性是多么重载,我不断得到很多错误的引导和死胡同。

6 个答案:

答案 0 :(得分:3)

使用MemberInfo.GetCustomAttributes

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

编辑:

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

祝你好运!

答案 1 :(得分:2)

试试这个:

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

答案 2 :(得分:1)

GetCustomAttributes是您想要使用的方法。

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

答案 3 :(得分:1)

我通常会使用一组扩展方法:

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 :(得分:0)

您需要使用GetCustomAttributes方法。

答案 5 :(得分:0)

您应该可以使用PropertyInfo实例上的MemberInfo.GetCustomAttributes来获取该属性。