从属性走到CustomAttributeData或向后走 [英] Walk from Attribute to CustomAttributeData or backwards
问题描述
问题。是否有一种方法可以根据我的自定义属性的给定实例(例如<$ c)获取 CustomAttributeData
的实例$ c> MyAttribute ?或反之亦然?
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?
为什么要这样做? MyAttribute
的实例包含我感兴趣的属性,而 CustomAttributeData
的实例包含我感兴趣的实际构造函数参数。因此,现在实现双重工作: first ,获取 MyAttribute
的实例,方法是调用
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
和 second ,获取实例 CustomAttributeData
通过调用
CustomAttributeData.GetCustomAttributes(property)
,然后遍历此收藏集。
P 。 S。。我查看了这个问题,但没有在此处找到所需的解决方案。
P. S. I have taken a look on this question, but didn't find the desired solution there.
推荐答案
如果我正确理解了您的问题,那么您已经有一个自定义属性MyAttributeInstance的实例,并且您想为同一实例获取CustomAttributeData,最好是一步完成。
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.
由于您已经找到MyAttributeInstance,并且该属性已附加到属性(或类或...)上,因此我假定您具有该属性。因此,这可能可能为您工作:
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());
我认为这回答了您的实际问题。但是,我认为您的意图可能实际上是在询问如何直接从属性获取CustomAttributeData。在这种情况下,请尝试以下操作:
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));
这篇关于从属性走到CustomAttributeData或向后走的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!