我怎样才能用C#优雅地做到这一点?
例如,数字可以介于1和100之间。
我知道一个简单的if (x >= 1 && x <= 100)
就足够了;但是随着大量的语法糖和新特性不断地添加到C#/.Net中,这个问题是关于更地道的(优雅的)方式来编写它。
性能不是问题,但请将性能注释添加到不是O(1)的解决方案中,因为人们可能会复制粘贴建议。
发布于 2010-07-07 01:32:26
你的意思是?
if(number >= 1 && number <= 100)
或
bool TestRange (int numberToCheck, int bottom, int top)
{
return (numberToCheck >= bottom && numberToCheck <= top);
}
发布于 2013-09-21 01:03:30
在生产代码中,我会简单地写成
1 <= x && x <= 100
这很容易理解,而且可读性很好。
从C#9.0开始,我们可以编写
x is >= 1 and <= 100
// Note that we must write x only once. "is" introduces a pattern matching
// expression where "and" is part of the pattern.
// "&&" would require us to repeat "x is": x is >= 1 && x is <= 100
这里有一个聪明的方法,通过使用一些数学将比较的次数从两次减少到一次。其思想是,如果数字超出范围,则两个因子中的一个变为负数,如果数字等于其中一个界限,则变为零:
如果边界是包含的:
(x - 1) * (100 - x) >= 0
或
(x - min) * (max - x) >= 0
如果边界是独占的:
(x - 1) * (100 - x) > 0
或
(x - min) * (max - x) > 0
发布于 2010-07-07 01:35:16
为了增加这里的干扰,您可以创建一个扩展方法:
public static bool IsWithin(this int value, int minimum, int maximum)
{
return value >= minimum && value <= maximum;
}
这会让你做一些像这样的事情。
int val = 15;
bool foo = val.IsWithin(5,20);
也就是说,当检查本身只有一行时,这似乎是一件愚蠢的事情。
https://stackoverflow.com/questions/3188672
复制相似问题