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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With