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

前端 未结 9 1077
野的像风
野的像风 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:50

    Using the previous answers, I condensed it down to the below code for my needs. This will also allow you to clamp a number only by its min or max.

    public static class IComparableExtensions
    {
        public static T Clamped(this T value, T min, T max) 
            where T : IComparable
        {
            return value.CompareTo(min) < 0 ? min : value.ClampedMaximum(max);
        }
    
        public static T ClampedMinimum(this T value, T min)
            where T : IComparable
        {
            return value.CompareTo(min) < 0 ? min : value;
        }
    
        public static T ClampedMaximum(this T value, T max)
            where T : IComparable
        {
            return value.CompareTo(max) > 0 ? max : value;
        }
    }
    

提交回复
热议问题