如何强制号是在一个范围在C#?是在、范围

2023-09-03 00:48:32 作者:草莓味的风

在C#中,我经常要限制一个整数值值的范围。例如,如果应用程序希望的百分比,从用户输入的整数必须不小于零或超过一百。另一个例子:如果有5它们通过 Request.Params访问的网页[P] ,我期望的值从1到5,而不是0或256或99999

我经常写一个相当难看code类端:

 页= Math.Max​​(0,Math.Min(2页));
 

甚至是丑陋的:

 比例=
    (inputPercentage℃,|| inputPercentage→100)?
    0:
    inputPercentage;
 
人人都在追捧Python,殊不知最会赚钱的是它

还没有一个更聪明的方式.NET框架中做出这样的事情?

我知道我可以写一个通用的方法 INT LimitToRange(int值,诠释inclusiveMinimum,INT inlusiveMaximum),并用它在每一个项目中,但也许已经有一个神奇的法的框架?

如果我需要做手工,这将是最好的(即更少的丑陋,更快速)的方式做我在做什么,在第一个例子?像这样的事情?

 公众诠释LimitToRange(int值,诠释inclusiveMinimum,INT inlusiveMaximum)
{
    如果(值GT = inclusiveMinimum)
    {
        如果(值小于= inlusiveMaximum)
        {
            返回值;
        }

        返回inlusiveMaximum;
    }

    返回inclusiveMinimum;
}
 

解决方案

我看到马克的回答,并提高它

 公共静态类InputExtensions
{
    公共静态INT LimitToRange(
        该int值,诠释inclusiveMinimum,INT inclusiveMaximum)
    {
        如果(值小于; inclusiveMinimum){返回inclusiveMinimum; }
        如果(值GT; inclusiveMaximum){返回inclusiveMaximum; }
        返回值;
    }
}
 

用法:

  INT userInput = ...;

INT结果= userInput.LimitToRange(1,5)
 

请参阅:扩展方法

In C#, I often have to limit an integer value to a range of values. For example, if an application expects a percentage, an integer from a user input must not be less than zero or more than one hundred. Another example: if there are five web pages which are accessed through Request.Params["p"], I expect a value from 1 to 5, not 0 or 256 or 99999.

I often end by writing a quite ugly code like:

page = Math.Max(0, Math.Min(2, page));

or even uglier:

percentage =
    (inputPercentage < 0 || inputPercentage > 100) ?
    0 :
    inputPercentage;

Isn't there a smarter way to do such things within .NET Framework?

I know I can write a general method int LimitToRange(int value, int inclusiveMinimum, int inlusiveMaximum) and use it in every project, but maybe there is already a magic method in the framework?

If I need to do it manually, what would be the "best" (ie. less uglier and more fast) way to do what I'm doing in the first example? Something like this?

public int LimitToRange(int value, int inclusiveMinimum, int inlusiveMaximum)
{
    if (value >= inclusiveMinimum)
    {
        if (value <= inlusiveMaximum)
        {
            return value;
        }

        return inlusiveMaximum;
    }

    return inclusiveMinimum;
}

解决方案

I see Mark's answer and raise it by a this:

public static class InputExtensions
{
    public static int LimitToRange(
        this int value, int inclusiveMinimum, int inclusiveMaximum)
    {
        if (value < inclusiveMinimum) { return inclusiveMinimum; }
        if (value > inclusiveMaximum) { return inclusiveMaximum; }
        return value;
    }
}

Usage:

int userInput = ...;

int result = userInput.LimitToRange(1, 5)

See: Extension Methods