Use reflection to get attribute of a property via method called from the setter

后端 未结 3 1054
长发绾君心
长发绾君心 2021-01-03 03:48

Note: This is a follow-up to an answer on a previous question.

I\'m decorating a property\'s setter with an Attribute called TestMaxStringLength

3条回答
  •  别那么骄傲
    2021-01-03 04:03

    You could consider, as an alternative approach, delaying validation until later, thus removing the need to inspect the stack trace.

    This example provides an attribute...

    public class MaxStringLengthAttribute : Attribute
    {
        public int MaxLength { get; set; }
        public MaxStringLengthAttribute(int length) { this.MaxLength = length; }
    }
    

    ... a POCO with the attribute applied to a property...

    public class MyObject
    {
        [MaxStringLength(50)]
        public string CompanyName { get; set; }
    }
    

    ... and a utility class stub that validates the object.

    public class PocoValidator
    {
        public static bool ValidateProperties(TValue value)
        {
            var type = typeof(TValue);
            var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (var prop in props)
            {
                var atts = prop.GetCustomAttributes(typeof(MaxStringLengthAttribute), true);
                var propvalue = prop.GetValue(value, null);
    
                // With the atts in hand, validate the propvalue ...
                // Return false if validation fails.
            }
    
            return true;
        }
    }
    

提交回复
热议问题