【问题标题】:Walk from Attribute to CustomAttributeData or backwards从 Attribute 走到 CustomAttributeData 或向后
【发布时间】:2016-05-11 12:41:59
【问题描述】:

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

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

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

,通过调用获取CustomAttributeData的实例

CustomAttributeData.GetCustomAttributes(property)

走过这个收藏。

P. S.我查看了this question,但没有找到所需的解决方案。

【问题讨论】:

    标签: c# reflection custom-attributes system.reflection


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 感谢您的回答。在我看来(但我记不清了)我问的是如何拥有一个 Attribute 类的实例,获取一个 CustomAttributeData 类的实例。在这种情况下,您的回答仅建议在拥有 PropertyInfo 类实例的同时获取 CustomAttributeData 类实例的另一种方法(问题中提出了另一种方法)。
    • 如果您有两个相同类型的属性应用于一个属性,此代码将给出第一个的值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2013-01-22
    • 2021-06-09
    • 2015-10-24
    • 2020-12-14
    • 1970-01-01
    • 2023-01-21
    相关资源
    最近更新 更多