假设您想将零或txtNumerator.Text传递给方法M。你该怎么做?
您可以这样写:
string argument;
if (txtNumerator.Text == "")
{
argument = "0";
}
else
{
argument = txtNumerator.Text;
}
M(argument);
或者你可以这样说
M(txtNumerator.Text == "" ? "0" : txtNumerator.Text);
后者更短且易于阅读。
本质上,语句由于其副作用而有用,表达式由于其值而有用。如果您想要控制哪种副作用发生,则使用“if”语句。如果您想要控制从两个可能性中选择哪个值,则考虑使用条件表达式。
更新:
珍妮问为什么不只是这样做?
if (txtNumerator.Text == "")
{
M("0");
}
else
{
M(txtNumerator.Text);
}
如果只有一个条件要检查,那就没问题。但是如果有四个呢?现在就有十六种可能性,编写相应的“if”语句变得非常混乱:
if (text1.Text == "")
{
if (text2.Text == "")
{
if (text3.Text == "")
{
if (text4.Text == "")
{
M("1", "2", "3", "4");
}
else
{
M("1", "2", "3", text4.Text);
}
}
else
{
if (text4.Text == "")
{
M("1", "2", text3.Text, "4");
}
else
{
M("1", "2", text3.Text, text4.Text);
}
}
... about fifty more lines of this.
相反,您可以只是说:
M(Text1.Text == "" ? "1" : Text1.Text,
Text2.Text == "" ? "2" : Text2.Text,
Text3.Text == "" ? "3" : Text3.Text,
Text4.Text == "" ? "4" : Text4.Text);