假设您想将零或 txtNumerator.Text 传递给方法 M。您会如何执行此操作?
你可以说:
string argument;
if (txtNumerator.Text == "")
{
argument = "0";
}
else
{
argument = txtNumerator.Text;
}
M(argument);
或者你可以说
M(txtNumerator.Text == "" ? "0" : txtNumerator.Text);
后者更短且更易于阅读。
这里更重要的一点是声明对他们有用副作用 and 表达式对他们有用values。如果您想要控制两个副作用中哪一个发生,请使用“if”语句。如果您想要控制从两种可能性中选择哪个值,请考虑使用条件表达式。
UPDATE:
珍妮问为什么不这样做呢?
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);