问题
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.
回答1:
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));
来源:https://stackoverflow.com/questions/35158061/walk-from-attribute-to-customattributedata-or-backwards