Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I get the property belonging to a custom attribute?

I need to find the type of the property that a custom attribute is applied to from within the custom attribute.

For example:

[MyAttribute]
string MyProperty{get;set;}

Given the instance of MyAttribute, how could I get a Type descriptor for MyProperty?

In other words, I am looking for the opposite of System.Type.GetCustomAttributes()

like image 549
Adrian Grigore Avatar asked May 27 '09 17:05

Adrian Grigore


1 Answers

The attribute itself knows nothing about the object that was decorated with it. But you could inject this information at the time you retrive the attribute.
At some point you have to retrieve the property using code similar to the following.

PropertyInfo propertyInfo = typeof(MyType).GetProperty("MyProperty");

Object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyAttribute), true);

if (attribute.Length > 0)
{
    MyAttribute myAttribute = (MyAttribute) attributes[0];

    // Inject the type of the property.
    myAttribute.PropertyType = propertyInfo.PropertyType;

    // Or inject the complete property info.
    myAttribute.PropertyInfo = propertyInfo;
}
like image 75
Daniel Brückner Avatar answered Sep 28 '22 10:09

Daniel Brückner