Go from attribute to attribute CustomAttributeData or back

Question. Is there a way to get an instance CustomAttributeDatabased on a given instance of my user attribute, say MyAttribute? Or vice versa?

Why do I need it? The instance MyAttributecontains the properties that interest me, while the instance CustomAttributeDatacontains the actual constructor parameters that interest me. So now I am implementing a double job: first, get the instance MyAttributeby calling

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

and secondly, get an instance CustomAttributeDataby calling

CustomAttributeData.GetCustomAttributes(property)

and strolling through this collection.

R. S. I examined this issue , but did not find the desired solution there.

+4
source share
1 answer

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

Since you have already found MyAttributeInstance and are tied to a property (or class or ...), I will assume that you have an available property. So this might work for you:

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

I think this answers your real question. However, I think your intention was to really ask how to get the CustomAttributeData property from the property directly. In this case, try the following:

CustomAttributeData CAD = property.GetCustomAttributesData().First(x => x.AttributeType == typeof(MyAttribute));
+1
source

Source: https://habr.com/ru/post/1627049/


All Articles