How to I get the property belonging to a custom attribute?

前端 未结 2 2117
离开以前
离开以前 2021-02-20 16:04

I need to find the type of the property that a custom attribute is applied to from within the custom attribute.

For example:

[MyAttribute]
string MyProp         


        
相关标签:
2条回答
  • 2021-02-20 16:31

    The attribute itself knows nothing about the object that was decorated with it. But you could inject this information at the time you retrive the attribute.
    At some point you have to retrieve the property using code similar to the following.

    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;
    }
    
    0 讨论(0)
  • 2021-02-20 16:38

    The custom attribute knows nothing about the attributed element so I don't think what you want is possible to do unless you enumerate all types in your system and check if they contain such attribute.

    0 讨论(0)
提交回复
热议问题