简体   繁体   English

C#if else快捷方式

[英]C# if else shortcut

In C# how can I express the following if else statement using a shorter method(with ?): 在C#中,如何使用较短的方法(带?)表示以下if else语句:

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

           }
           else if (condition2 == false)
           {

               dothismethod(value);
           }

My code looks really messy with these statements. 我的代码看起来非常混乱这些陈述。 Can someone direct me to a good resource on if then else short cut syntax? 有人可以指导我一个很好的资源,如果那么其他捷径语法?

It sounds like you're trying to write 这听起来像你正在努力写作

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

? is not a "shortcut" if/else. 如果是/否则不是“捷径”。 It's called a ternary operator , and it's used when you want to assign a value to some variable based on a condition, like so: 它被称为三元运算符 ,当您想根据条件为某个变量赋值时使用它,如下所示:

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

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

Your can write it like: 你可以这样写:

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

But personally, I would define your first expression as another variable, so your if statement becomes clearer: 但就个人而言,我会将您的第一个表达式定义为另一个变量,因此您的if语句会变得更清晰:

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

The conditional operator ? 条件运算符? only works for value assignment. 仅适用于价值分配。 But you can definitely fold both if's into one since the result is the same for both: 但是你肯定可以将两者都折叠成一个,因为两者的结果是相同的:

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

Or even more concise as: 或者更简洁如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM