使用带有快捷方式的if else条件

时间:2013-05-28 11:28:51

标签: c#

以下是我的代码:

代码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");
}

如果条件允许我使用内联编写此代码。

4 个答案:

答案 0 :(得分: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 ...

答案 1 :(得分: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" ) );

答案 2 :(得分:0)

请参阅此Wikipedia article

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

答案 3 :(得分:0)

它被称为ternairy运算符: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")

括号最适合保持其可读性,但多余。更好地保持可读性只是在非常短的表达中使用它。