为什么让事情变得更复杂?为什么这样做:
txtNumerator.Text =
txtNumerator.Text == "" ? "0" : txtNumerator.Text;
Run Code Online (Sandbox Code Playgroud)
而不是这个:
if txtNumerator.Text="" {txtNumerator.Text="0";}
Run Code Online (Sandbox Code Playgroud)
Eri*_*ert 32
假设你想要将零或txtNumerator.Text传递给方法M.你会怎么做?
你可以说:
string argument;
if (txtNumerator.Text == "")
{
argument = "0";
}
else
{
argument = txtNumerator.Text;
}
M(argument);
Run Code Online (Sandbox Code Playgroud)
或者你可以说
M(txtNumerator.Text == "" ? "0" : txtNumerator.Text);
Run Code Online (Sandbox Code Playgroud)
后者更短,更容易阅读.
这里更重要的一点是语句对于它们的副作用很有用,并且表达式对它们的值很有用.如果你想要做的是控制两个副作用中的哪一个发生,那么使用"if"语句.如果你想要做的是控制从两种可能性中选择哪个值,那么考虑使用条件表达式.
更新:
珍妮问为什么不这样做呢?
if (txtNumerator.Text == "")
{
M("0");
}
else
{
M(txtNumerator.Text);
}
Run Code Online (Sandbox Code Playgroud)
如果只有一个条件需要检查,那就没关系了.但是,如果有四个呢?现在有十六种可能性,为它编写"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.
Run Code Online (Sandbox Code Playgroud)
相反,你可以说:
M(Text1.Text == "" ? "1" : Text1.Text,
Text2.Text == "" ? "2" : Text2.Text,
Text3.Text == "" ? "3" : Text3.Text,
Text4.Text == "" ? "4" : Text4.Text);
Run Code Online (Sandbox Code Playgroud)
它是一个表达式,因此您可以直接在赋值或函数调用中使用结果,而无需复制您正在使用它的上下文.这使得许多使用场景的写入和读取都更加清晰.例如:
int abs = (x >= 0) ? x : -x;
Run Code Online (Sandbox Code Playgroud)
与
int abs;
if (x >= 0)
abs = x;
else
abs = -x;
Run Code Online (Sandbox Code Playgroud)