2011-04-11 44 views
2

我想实现一个简单的API,用户可以通过属性属性来指定对象属性的排序。如何检索C#中属性的属性?

是这样的:

[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写了一个自定义类,但一旦我在那里就是我会被卡住试图检索[排序]属性。目前,我有一些看起来像这样:

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

我想我可以使用xInfo.Attributes,但PropertyAttributes类并没有做什么,我需要做的。有没有人有任何指导如何检索[排序]属性?我已经环顾了很多人,但是在编程时如何超载属性这个词,我不断收到大量虚假的线索和死胡同。

回答

3

使用MemberInfo.GetCustomAttributes

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

编辑:

要获得本身的价值,看看this answer

祝你好运!

0

您需要使用GetCustomAttributes方法。

2

试试这个:

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

这将检索类上的任何自定义属性,而不是属性上的SortingAttribute。 – Greg 2011-04-11 17:33:49

+0

正确的是,同样的想法虽然... propertyInfo.GetCustomAttributes(布尔); – BrandonZeider 2011-04-11 17:47:41

1

GetCustomAttributes是你将要使用的方法。

SortingAttribute[] xAttributes = (SortingAttribute[])xInfo.GetCustomAttributes(typeof(SortingAttribute), true); 
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); 

从设计的角度来看,虽然,我会确保你只检查这些作为反思的特性并不总是很快。如果您正在比较多个对象,则可能会发现使用反射会成为一个瓶颈。