Check if property has attribute

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

    If you are using .NET 3.5 you might try with Expression trees. It is safer than reflection:

    class CustomAttribute : Attribute { }
    
    class Program
    {
        [Custom]
        public int Id { get; set; }
    
        static void Main()
        {
            Expression> expression = p => p.Id;
            var memberExpression = (MemberExpression)expression.Body;
            bool hasCustomAttribute = memberExpression
                .Member
                .GetCustomAttributes(typeof(CustomAttribute), false).Length > 0;
        }
    }
    

提交回复
热议问题