Check if property has attribute

前端 未结 8 1535
刺人心
刺人心 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:42

    You can use the Attribute.IsDefined method

    https://msdn.microsoft.com/en-us/library/system.attribute.isdefined(v=vs.110).aspx

    if(Attribute.IsDefined(YourProperty,typeof(YourAttribute)))
    {
        //Conditional execution...
    }
    

    You could provide the property you're specifically looking for or you could iterate through all of them using reflection, something like:

    PropertyInfo[] props = typeof(YourClass).GetProperties();
    
    0 讨论(0)
  • 2020-11-28 03:45

    You can use a common (generic) method to read attribute over a given MemberInfo

    public static bool TryGetAttribute<T>(MemberInfo memberInfo, out T customAttribute) where T: Attribute {
                    var attributes = memberInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault();
                    if (attributes == null) {
                        customAttribute = null;
                        return false;
                    }
                    customAttribute = (T)attributes;
                    return true;
                }
    
    0 讨论(0)
提交回复
热议问题