MinValue & MaxValue attribute for properties

前端 未结 5 2204
花落未央
花落未央 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:13

    You can elegantly solve this problem by using PostSharp by writing simple aspect, free version will be enough for this purpose:

    [Serializable]
    class RangeAttribute : LocationInterceptionAspect 
    {
        private int min;
        private int max;
    
        public RangeAttribute(int min, int max)
        {
            this.min = min;
            this.max = max;
        }
    
        public override void OnSetValue(LocationInterceptionArgs args)
        {
            int value = (int)args.Value;
            if (value < min) value = min;
            if (value > max) value = max;            
            args.SetNewValue(value);
        }
    }
    

    and then exacly as you want:

    class SomeClass
    {
        [Range(1, 50)]
        public int Size { get; set; }
    }
    

    with normal usage:

    var c = new SomeClass();
    c.Size = -3;
    Console.Output(c.Size);
    

    will output 1.

提交回复
热议问题