【问题标题】:How to I get the property belonging to a custom attribute?如何获取属于自定义属性的属性?
【发布时间】:2010-10-29 08:23:38
【问题描述】:

我需要从自定义属性中找到应用自定义属性的属性类型。

例如:

[MyAttribute]
string MyProperty{get;set;}

给定 MyAttribute 的实例,我如何获得 MyProperty 的类型描述符?

换句话说,我正在寻找 System.Type.GetCustomAttributes() 的反面

【问题讨论】:

  • 你最好把你想做的事说出来,因为你问的是不可能的。

标签: c# reflection attributes


【解决方案1】:

属性本身对用它装饰的对象一无所知。但是您可以在检索属性时注入此信息。
在某些时候,您必须使用类似于以下的代码来检索属性。

PropertyInfo propertyInfo = typeof(MyType).GetProperty("MyProperty");

Object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyAttribute), true);

if (attribute.Length > 0)
{
    MyAttribute myAttribute = (MyAttribute) attributes[0];

    // Inject the type of the property.
    myAttribute.PropertyType = propertyInfo.PropertyType;

    // Or inject the complete property info.
    myAttribute.PropertyInfo = propertyInfo;
}

【讨论】:

  • 我需要这个来解决我的问题,我找到了another solution here。我对此进行了详细说明并发布了一个响应,以访问属性而不是类的自定义属性。顺便说一句,谢谢!
【解决方案2】:

自定义属性对属性元素一无所知,因此我认为除非您枚举系统中的所有类型并检查它们是否包含此类属性,否则您无法做到。

【讨论】:

    猜你喜欢
    • 2019-05-20
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多