我在哪里可以找到"钳QUOT;在.NET函数? [英] Where can I find the "clamp" function in .NET?

查看:148
本文介绍了我在哪里可以找到"钳QUOT;在.NET函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想钳制值 X 一系列 [A,B]

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

这是很基本的。但我没有看到类库中的函数钳 - 至少在 System.Math

This is quite basic. But I do not see a function "clamp" in the class library - at least not in System.Math.

(对于不知道为夹紧的值是要确保它位于一些最大值和最小值之间,如果它比最大值大,则它是由最大值代替,等等。)

(For the unaware to "clamp" a value is to make sure that it lies between some maximum and minimum values. If it’s greater than the max value, then it’s replaced by the max, etc.)

推荐答案

您可以写一个扩展方法:

You could write an extension method:

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

编辑:扩展方法去静态类 - 因为这是一个相当低的水平的功能,它或许应该走在你的项目中一些核心命名空间。然后,您可以使用该方法在包含using指令为命名空间例如任何code文件。

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);

这篇关于我在哪里可以找到&QUOT;钳QUOT;在.NET函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆