问题描述
如何使用 C# 优雅地做到这一点?
How can I do this elegantly with C#?
例如,一个数字可以介于 1 和 100 之间.
For example, a number can be between 1 and 100.
我知道一个简单的 if (x >= 1 && x <= 100)
就足够了;但是随着大量语法糖和不断添加到 C#/.Net 中的新功能,这个问题是关于更惯用(一个可以是优雅)的编写方式.
I know a simple if (x >= 1 && x <= 100)
would suffice; but with a lot of syntax sugar and new features constantly added to C#/.Net this question is about more idiomatic (one can all it elegance) ways to write that.
性能不是问题,但请在不是 O(1) 的解决方案中添加性能说明,因为人们可能会复制粘贴建议.
Performance is not a concern, but please add performance note to solutions that are not O(1) as people may copy-paste the suggestions.
推荐答案
有很多选择:
int x = 30;
if (Enumerable.Range(1,100).Contains(x)) //true
事实上,基本的 if
可以在第一次检查中以相反的顺序更优雅地编写:
And indeed basic if
more elegantly can be written with reversing order in the first check:
if (1 <= x && x <= 100) //true
另外,请查看此 SO 帖子,了解正则表达式选项.
Also, check out this SO post for regex options.
注意事项:
LINQ 解决方案严格用于样式点 - 因为 Contains 迭代所有项目,它的复杂性是 O(range_size) 而不是 O(1),通常是范围检查所期望的.
其他范围的更通用版本(注意第二个参数是计数,而不是结束):
LINQ solution is strictly for style points - since Contains iterates over all items its complexity is O(range_size) and not O(1) normally expected from a range check.
More generic version for other ranges (notice that second argument is count, not end):
if (Enumerable.Range(start, end - start + 1).Contains(x)
没有&&
这样的if
解决方案是很有诱惑力的,比如1 <= x <= 100
-看起来很优雅,但在 C# 中会导致语法错误Operator '<=' cannot be applied to operands of type 'bool' and 'int'"
There is temptation to write if
solution without &&
like 1 <= x <= 100
- that look really elegant, but in C# leads to a syntax error "Operator '<=' cannot be applied to operands of type 'bool' and 'int'"
这篇关于如何优雅地检查一个数字是否在一个范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!