Where can I find the “clamp” function in .NET?

前端 未结 9 1072
野的像风
野的像风 2020-11-27 04:24

I would like to clamp a value x to a range [a, b]:

x = (x < a) ? a : ((x > b) ? b : x);

This is quite basic

9条回答
  •  迷失自我
    2020-11-27 04:53

    If I want to validate the range of an argument in [min, max], the I use the following handy class:

    public class RangeLimit where T : IComparable
    {
        public T Min { get; }
        public T Max { get; }
        public RangeLimit(T min, T max)
        {
            if (min.CompareTo(max) > 0)
                throw new InvalidOperationException("invalid range");
            Min = min;
            Max = max;
        }
    
        public void Validate(T param)
        {
            if (param.CompareTo(Min) < 0 || param.CompareTo(Max) > 0)
                throw new InvalidOperationException("invalid argument");
        }
    
        public T Clamp(T param) => param.CompareTo(Min) < 0 ? Min : param.CompareTo(Max) > 0 ? Max : param;
    }
    

    The class works for all object which are IComparable. I create an instance with a certain range:

    RangeLimit range = new RangeLimit(0, 100);
    

    I an either validate an argument

    range.Validate(value);
    

    or clamp the argument to the range:

    var v = range.Validate(value);
    

提交回复
热议问题