Check if property has attribute

前端 未结 8 1543
刺人心
刺人心 2020-11-28 03:03

Given a property in a class, with attributes - what is the fastest way to determine if it contains a given attribute? For example:

    [IsNotNullable]
    [I         


        
8条回答
  •  旧巷少年郎
    2020-11-28 03:33

    If you are trying to do that in a Portable Class Library PCL (like me), then here is how you can do it :)

    public class Foo
    {
       public string A {get;set;}
    
       [Special]
       public string B {get;set;}   
    }
    
    var type = typeof(Foo);
    
    var specialProperties = type.GetRuntimeProperties()
         .Where(pi => pi.PropertyType == typeof (string) 
          && pi.GetCustomAttributes(true).Any());
    

    You can then check on the number of properties that have this special property if you need to.

提交回复
热议问题