Walk from Attribute to CustomAttributeData or backwards

爷,独闯天下 提交于 2019-12-23 09:25:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!