使用三元运算符而不是IF那么有什么意义呢?
为什么让事情变得更复杂? 为什么这样做:
txtNumerator.Text = txtNumerator.Text == "" ? "0" : txtNumerator.Text;
而不是这个:
if txtNumerator.Text="" {txtNumerator.Text="0";}
假设你想将零或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);
它是一个表达式,因此您可以直接在赋值或函数调用中使用结果,而无需复制您正在使用它的上下文。 这使得许多使用场景的写入和读取更加清晰。 例如:
int abs = (x >= 0) ? x : -x;
与
int abs; if (x >= 0) abs = x; else abs = -x;
有许多标准指南说不使用三元运算符。 但是你可能会认为除了goto和if之外,所有语言function都是不必要的。 如果那么多的话,我会使用它。
它使得代码在某些人的意见中更具可读性,语言中的许多结构都是语法糖(想想do..while,while..do和for(..))以及在你选择的那一天结束时对你(和你的团队)有用。
我举例说,我认为上面的代码应该用扩展方法实现:
txtNumerator.SetDefault("0");
如果使用if-then结构,最终会在两个单独的块中对同一个变量进行两次赋值。 三元forms只有一个任务。 因此,无需查看第二个块来validation两个块对同一变量执行赋值的内容。 在这方面,我认为三元forms更好。
另一方面,如果C#像Ruby一样工作并且if是表达式,那么你可以不使用三元运算符并在这种情况下使用if-else:
txtNumerator.Text = if (txtNumerator.Text == "" ) "0"; else (txtNumerator.Text);
我更喜欢,因为那时可以删除?:的不同语法。