6

在 C# 中,如何使用更短的方法(使用?)来表达以下 if else 语句:

 if (condition1 == true && count > 6)
           {
               dothismethod(value);

           }
           else if (condition2 == false)
           {

               dothismethod(value);
           }

我的代码与这些语句看起来真的很乱。有人可以指导我找到有关 if then else 快捷语法的好资源吗?

4

4 回答 4

19

听起来你正在尝试写

if ((condition1 && count > 6) || !condition2)
    SomeMethod();
于 2012-11-21T23:13:05.457 回答
9

?不是“捷径” if/else。它被称为三元运算符,当您想根据条件为某个变量赋值时使用它,如下所示:

string message = hasError ? "There's an error!" : "Everything seems fine...";

MSDN:http: //msdn.microsoft.com/en-us/library/ty67wk28%28v=vs.100%29.aspx

于 2012-11-21T23:15:57.473 回答
4

你可以这样写:

if ((condition1 == true && count > 6) || condition2 == false)
{
    dothismethod(value);
}

但就个人而言,我会将您的第一个表达式定义为另一个变量,因此您的 if 语句变得更加清晰:

bool meaningfulConditionName = (condition1 == true) && count > 6;
if (meaningfulConditionName || !condition2)
{
    dothismethod(value);
}
于 2012-11-21T23:24:25.983 回答
0

条件运算符?仅适用于赋值。但是你绝对可以将两个 if 合二为一,因为两者的结果是相同的:

if ((condition1 == true && count > 6) || condition2 == false)
           {
               dothismethod(value);
           }

或者更简洁:

if ((condition1 && count > 6) || !condition2) dothismethod(value);
于 2012-11-21T23:15:17.947 回答