c# - 从 Attribute 走到 CustomAttributeData 或向后

标签 c# reflection custom-attributes system.reflection

问题。有没有办法根据我的自定义属性的给定实例(比如 MyAttribute)获取 CustomAttributeData 的实例?还是相反?

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

获取MyAttribute的实例
Attribute.GetCustomAttribute(property, typeof(MyAttribute)) as MyAttribute

其次,通过调用获取CustomAttributeData的实例

CustomAttributeData.GetCustomAttributes(property)

然后遍历这个集合。

P. S. 我看过this question , 但在那里没有找到所需的解决方案。

最佳答案

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

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

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

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

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

关于c# - 从 Attribute 走到 CustomAttributeData 或向后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35158061/

相关文章:

c# - 返回 List<string[]> 而不是 string[][]

c# - SQLite:创建表并在表不存在时添加一行

asp.net-mvc - MVC - 使用数据库中的错误消息验证属性

reflection - 哪些情况难以区分代码和数据?

python - 绑定(bind)方法上的装饰器可以访问类及其祖先

c# - 检查通用接口(interface)成员是否为 "Pure"(具有纯属性)

c# - 将 ContextAttribute 与方法一起使用

c# - Visual Studio 项目创建事件

c# - AutoMapper 和 EF 实体 - 忽略所有关系

objective-c - 如何从objective-c类型编码中获取字节大小