Benefits of using the conditional ?: (ternary) operator

后端 未结 17 1009
孤街浪徒
孤街浪徒 2020-11-22 06:55

What are the benefits and drawbacks of the ?: operator as opposed to the standard if-else statement. The obvious ones being:

Conditional ?: Operator

17条回答
  •  粉色の甜心
    2020-11-22 07:47

    Sometimes it can make the assignment of a bool value easier to read at first glance:

    // With
    button.IsEnabled = someControl.HasError ? false : true;
    
    // Without
    button.IsEnabled = !someControl.HasError;
    

提交回复
热议问题