如何使用三元运算符最小化以下代码
if (toolButtonState.New == 1)
ts.Items["tsbNew"].Enabled = true;
else
ts.Items["tsbNew"].Enabled = false;
请提供一个实现
如何使用三元运算符最小化以下代码
if (toolButtonState.New == 1)
ts.Items["tsbNew"].Enabled = true;
else
ts.Items["tsbNew"].Enabled = false;
请提供一个实现
您不需要三元运算符。您可以像这样简化它:
ts.Items["tsbNew"].Enabled = (toolButtonState.New == 1);
从技术上讲,您可以使用这样的三元运算符,但没有理由:
ts.Items["tsbNew"].Enabled = (toolButtonState.New == 1) ? true : false;
?
通常,如果and之后的表达式:
不简单地计算为true
and ,则三元表达式更有用false
,例如:
someControl.ForeColor = (toolButtonState.New == 1) ? Color.Red : Color.Black;
请记住,如果表达式不仅仅是一个简单的单行代码,那么如果您只使用老式if/else
语句和花括号,您的代码可能更具可读性。
The ternary operator is of the form:
(condition) ? (if true) : (if false)
So a ternary on your piece of code would turn in to:
ts.Items["tsbNew"].Enabled = (toolButtonState.New == 1) ? true : false;
You will notice though that the if true value is true
and the if false value is false
. You can simply remove the ternary statement and it will do the same thing by setting .Enabled
to the result of the condition:
ts.Items["tsbNew"].Enabled = (toolButtonState.New == 1);