Csharp/C#教程:从Attribute转到CustomAttributeData或向后分享


从Attribute转到CustomAttributeData或向后

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

我为什么需要这个? MyAttribute的实例包含我感兴趣的属性,而CustomAttributeData的实例包含我感兴趣的实际构造函数参数。所以现在我实现了双重工作: 首先 ,通过调用获取MyAttribute的实例

 Attribute.GetCustomAttribute(property, typeof(MyAttribute)) as MyAttribute 

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

 CustomAttributeData.GetCustomAttributes(property) 

并走过这个系列。

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

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

由于您已经找到了MyAttributeInstance,并且附加到属性(或类或…),我将假设您拥有该属性。 所以这可能适合你:

 CustomAttributeData CAD = property.GetCustomAttributesData().First(x => x.AttributeType == MyAttributeInstance.GetType()); 

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

上述就是C#学习教程:从Attribute转到CustomAttributeData或向后分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 CustomAttributeData CAD = property.GetCustomAttributesData().First(x => x.AttributeType == typeof(MyAttribute)); 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/949531.html

(0)
上一篇 2021年11月17日
下一篇 2021年11月17日

精彩推荐