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

前端 未结 9 1037
野的像风
野的像风 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<T> where T : IComparable<T>
    {
        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<int> range = new RangeLimit<int>(0, 100);
    

    I an either validate an argument

    range.Validate(value);
    

    or clamp the argument to the range:

    var v = range.Validate(value);
    
    0 讨论(0)
  • 2020-11-27 05:03

    There isn't one, but it's not too hard to make one. I found one here: clamp

    It is:

    public static T Clamp<T>(T value, T max, T min)
        where T : System.IComparable<T> {
            T result = value;
            if (value.CompareTo(max) > 0)
                result = max;
            if (value.CompareTo(min) < 0)
                result = min;
            return result;
        }
    

    And it can be used like:

    int i = Clamp(12, 10, 0); -> i == 10
    double d = Clamp(4.5, 10.0, 0.0); -> d == 4.5
    
    0 讨论(0)
  • 2020-11-27 05:06

    There isn't one in the System.Math namespace.

    There is a MathHelper Class where it is available for the XNA game studio if that happens to be what you are doing:

    0 讨论(0)
提交回复
热议问题