我如何用c#优雅地做到这一点?

例如,一个数字可以是1到100之间。

我知道一个简单的if (x >= 1 && x <= 100)就足够了;但是有很多语法糖和新特性不断添加到c# /。Net这个问题是关于更习惯的(一个可以称之为优雅的)写法。

性能不是问题,但请在非O(1)的解决方案中添加性能说明,因为人们可能会复制粘贴建议。


当前回答

if (value > 1 && value < 100)
{
    // do work
}
else
{
    // handle outside of range logic
}

其他回答

if (value > 1 && value < 100)
{
    // do work
}
else
{
    // handle outside of range logic
}

有很多选择:

int x = 30;
if (Enumerable.Range(1,100).Contains(x))  //true

实际上,基本的,如果更优雅的话,可以在第一张支票中用倒序写:

if (1 <= x && x <= 100)   //true

此外,查看这篇SO帖子的正则表达式选项。

注:

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) 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'"

如果这是偶然的,你只需要一个简单的If。如果这种情况在很多地方都发生,你可能会考虑这两个:

PostSharp。在方法编译后,用“注入”代码的属性来装饰方法。我不确定,但我可以想象它可以用来做这个。

喜欢的东西:

[Between("parameter", 0, 100)]
public void Foo(int parameter)
{
}

代码合同。优点是可以在编译时通过对代码和使用代码的地方进行静态验证来检查约束。

关于优雅,最接近数学符号(a <= x <= b)的方法略微提高了可读性:

public static bool IsBetween(this int value, int min, int max)
{
    return min <= value && value <= max;
}

为了进一步说明:

public static bool IsOutside(this int value, int min, int max)
{
    return value < min || max < value;
}

通过一些扩展方法的滥用,我们可以得到以下“优雅”的解决方案:

using System;

namespace Elegant {
    public class Range {
        public int Lower { get; set; }
        public int Upper { get; set; }
    }

    public static class Ext {
        public static Range To(this int lower, int upper) {
            return new Range { Lower = lower, Upper = upper };
        }

        public static bool In(this int n, Range r) {
            return n >= r.Lower && n <= r.Upper;
        }
    }

    class Program {
        static void Main() {
            int x = 55;
            if (x.In(1.To(100)))
                Console.WriteLine("it's in range! elegantly!");
        }
    }
}