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

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

    You could write an extension method:

    public static T Clamp(this T val, T min, T max) where T : IComparable
    {
        if (val.CompareTo(min) < 0) return min;
        else if(val.CompareTo(max) > 0) return max;
        else return val;
    }
    

    Extension methods go in static classes - since this is quite a low-level function, it should probably go in some core namespace in your project. You can then use the method in any code file that contains a using directive for the namespace e.g.

    using Core.ExtensionMethods
    
    int i = 4.Clamp(1, 3);
    

    .NET Core 2.0

    Starting with .NET Core 2.0 System.Math now has a Clamp method that can be used instead:

    using System;
    
    int i = Math.Clamp(4, 1, 3);
    

提交回复
热议问题