开发者

How do I retrieve attributes on properties in C#?

I am trying to implement a simple API where a user can dictate the sorting of object properties with a property attribute.

Something like:

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

In the basic ToString() method, I then use reflection to pull the properties from the object.

Type currentType = this.GetType();
PropertyInfo[] propertyInfoArray = currentType.GetProperties(BindingFlags.Public);
A开发者_JAVA技巧rray.Sort(propertyInfoArray, this.comparer);

I have written a custom class using the IComparer interface to do the Array.Sort, but once I'm in there I get stuck trying to retrieve the [Sorting] attribute. I currently have something that looks like this:

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

I thought I could use xInfo.Attributes, but the PropertyAttributes class does not do what I need it to do. Does anyone have any guidance for how to retrieve that [Sorting] Attribute? I have looked around a lot, but with how overloaded the word Attribute is in programming I keep getting a lot of false leads and dead ends.


Use MemberInfo.GetCustomAttributes

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

Edit:

To get the value itself, have a look at this answer.

Good luck!


Try this:

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


I generally use a set of extension methods for this:

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>()
}

I can call it as:

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

From a design point of view though, I would ensure that you only inspect these properties as reflection isn't always quick. If you are comparing multiple objects, you may find the use of reflection to be a bit of a bottleneck.


GetCustomAttributes is the method you will want to use.

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


You need to use the GetCustomAttributes method.


You should be able to fetch the attribute using MemberInfo.GetCustomAttributes on the PropertyInfo instance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜