0

以下是我的代码:

代码 1:

int x = 10;

if (x < 10)
{
    if (x < 5)
    {
        MessageBox.Show("less than 5");
    }
    else
    {
        MessageBox.Show("value is between 5 and 10");
    }
}
else
{
    MessageBox.Show("grater than 10");
}

代码 2:

int x = 10;

if (x > 5 && x < 10)
{
    MessageBox.Show("Value is between 5 and 10");
}
else if (x < 5)
{
    MessageBox.Show("less than 5");
}                
else
{
    MessageBox.Show("grater than 10");
}

如何使用内联 if 条件编写此代码。

4

4 回答 4

3
int x=10;

MessageBox.Show( 
  x < 10 ? ( x < 5 ? "less than 5" : "between 5 and 10" ) : "greater than 10" 
);

尽管我建议不要使用复杂的三元语句 - 它们可能会变得非常混乱。

另请注意,greater than 10实际上应该是greater than or equal to 10...

于 2013-05-28T11:32:18.233 回答
1

即使您的原始代码存在多个问题,这里是您使用内联 ifs 的代码:

为了清楚起见,我添加了带括号的代码。

代码 1:

int x = 10;
MessageBox.Show(
    (x < 10) ?
    (
        (x < 5) ?
        (
            "less than 5"
        )
        :
        (
            "value is between 5 and 10"
        )
    )
    :
    (
        "grater than 10"
    )
);

在一行中:

int x = 10;
MessageBox.Show( (x < 10) ? ( (x < 5) ? "less than 5" : "value is between 5 and 10" ) : "grater than 10" );

代码 2:

int x = 10;
MessageBox.Show(
    (x > 5 && x < 10) ?
    (
        "Value is between 5 and 10"
    )
    : 
    (
        (x < 5) ?
        (
            "less than 5"
        )                
        :
        (
            "grater than 10"
        )
    )
);

在一行中:

int x = 10;
MessageBox.Show( (x > 5 && x < 10) ? "Value is between 5 and 10" : ( (x < 5) ? "less than 5" : "grater than 10" ) );
于 2013-05-28T11:57:37.997 回答
0

请参阅此维基百科文章

String message = (x > 10 ? "Greater than 10" : (x < 5 ? "Less than 5" : "Value is between 5 and 10"))

于 2013-05-28T11:32:09.157 回答
0

它被称为三元运算符:var = <condition> ? <value-if-true> : <value-if-false>

您可以按如下方式修改您的代码:

int x = 10;
MessageBox.Show(x < 10 ? (x < 5 ? "less than 5" : "value is between 5 and 10") : "grater than 10")

括号是保持可读性的最佳选择,但也是多余的。对于保持可读性更好的是仅在非常短的表达式上使用它。

于 2013-05-28T11:34:18.330 回答