C# if else 快捷方式

6
在C#中,如何使用更短的方法(使用?)表达以下if else语句:
 if (condition1 == true && count > 6)
           {
               dothismethod(value);

           }
           else if (condition2 == false)
           {

               dothismethod(value);
           }

我的代码看起来很杂乱,需要缩短if、then和else语句长度。请问有好的资源可以推荐吗?

4个回答

19

听起来你正在尝试写作。

if ((condition1 && count > 6) || !condition2)
    SomeMethod();

9

4
你可以这样写:

你可以像这样写:

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

但是个人建议将第一个表达式定义为另一个变量,这样您的if语句更清晰:

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

0

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

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

或者更加简洁地:

if ((condition1 && count > 6) || !condition2) dothismethod(value);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接