0

在 Python 中,我可以做这样的事情,我认为这比一个语句中的两对条件更清楚:

if 1 < 2 < 3:
  print 'triple testing?'

else:
  print 'more like triple failing!'

没有遇到任何问题,但在 C# 中,它将第一个比较转换1 < 2为 a bool,然后再继续,所以它抛出了一个异常Operator '<' cannot be applied to operands of type 'bool' and 'int'

有没有办法避免添加第二个条件,所以我不必像在 Python 中那样将三重条件分成两组,而不是一个“三重”条件?

if (1 < 2 & 2 < 3) { ... }

编辑:我使用它的一个例子是确保 anint在一系列数字之间。

if ((0 < x) && (x < 10) { ... } //I can already do this
vs
if (0 < x < 10) { ... } //Would rather have something like this
4

3 回答 3

6

分组条件。试试这个,

if ((1 < 2) && (2 < 3))
{
   // statements here
}
else
{
   // statements here
}
于 2012-09-24T00:33:49.870 回答
3

是的,有,您正在寻找

If ((1 < 2) && (2< 3)) { doWhatever(); }

&&是逻辑与运算符,还有||逻辑或。

于 2012-09-24T00:34:35.833 回答
2

1 < 2 < 3在 C#中没有办法。但是,您可以编写一个快速扩展方法来模仿它:

public static class Test
{
    public static bool IsSorted<T>(this IEnumerable<T> e)
    {
        return e.Zip(e.Skip(1), (a, b) => Comparer<T>.Default.Compare(a, b))
            .All(x => x <= 0);
    }
}

...

if (new[] { 1, 2, 3 }.IsSorted())
{
    // Do something
}

If 对于 3 个数字来说绝对是矫枉过正,但如果有更多值要比较或者它们没有硬编码,则可能很有用。

于 2012-09-24T00:59:13.120 回答