Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Walk from Attribute to CustomAttributeData or backwards

Question. Is there a way to get an instance of CustomAttributeData based on the given instance of my custom attribute, say, MyAttribute? Or vice versa?

Why do I need this? The instance of MyAttribute contains properties I am interested in, while the instance of CustomAttributeData contains actual constructor parameters I am interested in. So now I implement double work: first, get the instance of MyAttribute by calling

Attribute.GetCustomAttribute(property, typeof(MyAttribute)) as MyAttribute

, and second, get the instance of CustomAttributeData by calling

CustomAttributeData.GetCustomAttributes(property)

and walking over this collection.

P. S. I have taken a look on this question, but didn't find the desired solution there.

like image 491
Hoborg Avatar asked Feb 02 '16 15:02

Hoborg


Video Answer


1 Answers

If I understand your question correctly, you already have an instance of the custom attribute MyAttributeInstance, and you want to get the CustomAttributeData for that same instance, preferably in one step.

Since you already found the MyAttributeInstance, and that is attached to a property (or a class, or...), I will assume you have the property available. So this could possibly work for you:

CustomAttributeData CAD = property.GetCustomAttributesData().First(x => x.AttributeType == MyAttributeInstance.GetType());

I think that answers your actual question. However, I think your intent might have been to actually ask how to get the CustomAttributeData from a property directly. In that case try this:

CustomAttributeData CAD = property.GetCustomAttributesData().First(x => x.AttributeType == typeof(MyAttribute));
like image 66
Andy Avatar answered Nov 06 '22 22:11

Andy