MinValue & MaxValue attribute for properties

前端 未结 5 2194
花落未央
花落未央 2020-12-17 15:27

Is it possible to make attribute which can limit minimum or maximum value of numbers.

Example:

[MinValue(1), MaxValue(50)]
public int Size { get; set         


        
5条回答
  •  暖寄归人
    2020-12-17 16:14

    Yes, it is possible with (already pointed) CustomAttributes, but mind, that you will loose the comfort of the auto-properties - because you need to apply resp. check the attribute restriction somewhere and in this case an appropriate place would be the getter of the property, so the interesting part of the problem is the application of the attributes. You can read how to access custom attributes in this MSDN article.

    A possible solution for the MaxValue custom attribute can look like this:

    // simple class for the example
    public class DataHolder
    {
        private int a;
    
        [MaxValue(10)]
        public int A 
        { 
            get
            {
                var memberInfo = this.GetType().GetMember("A");
                if (memberInfo.Length > 0)
                {
                    // name of property could be retrieved via reflection
                    var mia = this.GetType().GetMember("A")[0];
                    var attributes = System.Attribute.GetCustomAttributes(mia);
                    if (attributes.Length > 0)
                    {
                        // TODO: iterate over all attributes and check attribute name
                        var maxValueAttribute = (MaxValue)attributes[0];
                        if (a > maxValueAttribute.Max) { a = maxValueAttribute.Max; }
                    }
                }
                return a;
            }
            set
            {
                a = value;
            }
        }
    }
    
    
    // max attribute
    public class MaxValue : Attribute
    {
        public int Max;
    
        public MaxValue(int max)
        {
            Max = max;  
        }
    }
    

    The sample usage:

    var data = new DataHolder();
    data.A = 12;
    Console.WriteLine(data.A);
    

    creates the output:

    10
    

    The code for the MinValue will look the same as for the MaxValue but the if condition will be less than instead of greater than.

提交回复
热议问题