Inheritance of Custom Attributes on Abstract Properties

前端 未结 5 1538
萌比男神i
萌比男神i 2020-12-01 20:42

I\'ve got a custom attribute that I want to apply to my base abstract class so that I can skip elements that don\'t need to be viewed by the user when displaying the item in

5条回答
  •  旧时难觅i
    2020-12-01 20:58

    Instead of calling PropertyInfo.GetCustomAttributes(...), you have to call the static method System.Attribute.GetCustomAttributes(pi,...), as in:

    PropertyInfo info = GetType().GetProperties();
    
    // this gets only the attributes in the derived class and ignores the 'true' parameter
    object[] DerivedAttributes = info.GetCustomAttributes(typeof(MyAttribute),true);
    
    // this gets all of the attributes up the heirarchy
    object[] InheritedAttributes = System.Attribute.GetCustomAttributes(info,typeof(MyAttribute),true);
    

提交回复
热议问题