? operator without else-part

后端 未结 3 1709
死守一世寂寞
死守一世寂寞 2020-12-11 00:05

I use C# ? operator when I have if-statements that affects one row and it\'s all good. But lets say I have this code (using classic if-statements):

if(someSt         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-11 00:39

    Basically, you're trying to use the conditional operator for something that it's not designed for.

    It's not meant to optionally take some action... it's meant to evaluate one expression or another, and that be the result of the expression.

    If you only want to perform an action when some condition is met, use an if statement - that's precisely what it's there for.

    In your example, you could use:

    // Renamed someStatement to someCondition for clarity
    someBool |= someCondition;
    

    or

    someBool = someCondition ? true : someBool;
    

    ... in other words "use the existing value unless someCondition is true... but personally, I think the original if statement is clearer.

提交回复
热议问题