从Attribute转到CustomAttributeData或向后

Hob*_*org 6 c# reflection custom-attributes system.reflection

题.有没有办法CustomAttributeData根据自定义属性的给定实例获取实例,比如说MyAttribute?或相反亦然?

我为什么需要这个?实例MyAttribute包含我感兴趣的属性,同时实例CustomAttributeData包含实际的构造函数的参数我很感兴趣,所以,现在我实现了双重的工作:第一,得到的实例MyAttribute调用

Attribute.GetCustomAttribute(property, typeof(MyAttribute)) as MyAttribute
Run Code Online (Sandbox Code Playgroud)

,第二,CustomAttributeData通过调用获取实例

CustomAttributeData.GetCustomAttributes(property)
Run Code Online (Sandbox Code Playgroud)

并走过这个系列.

PS我已经看过这个问题,但没有在那里找到理想的解决方案.

And*_*ndy 2

如果我正确理解您的问题,则您已经拥有自定义属性 MyAttributeInstance 的实例,并且您希望获取同一实例的 CustomAttributeData,最好一步完成。

由于您已经找到了 MyAttributeInstance,并且它附加到一个属性(或一个类,或...),我将假设您拥有可用的属性。所以这可能你有用:

CustomAttributeData CAD = property.GetCustomAttributesData().First(x => x.AttributeType == MyAttributeInstance.GetType());
Run Code Online (Sandbox Code Playgroud)

我认为这回答了你的实际问题。但是,我认为您的意图可能是实际询问如何直接从属性获取 CustomAttributeData。在这种情况下试试这个:

CustomAttributeData CAD = property.GetCustomAttributesData().First(x => x.AttributeType == typeof(MyAttribute));
Run Code Online (Sandbox Code Playgroud)