【发布时间】:2011-04-24 00:23:58
【问题描述】:
为什么要让事情变得更复杂?为什么这样做:
txtNumerator.Text =
txtNumerator.Text == "" ? "0" : txtNumerator.Text;
而不是这个:
if txtNumerator.Text="" {txtNumerator.Text="0";}
【问题讨论】:
-
我想你会喜欢 ??运算符。
标签: c#
为什么要让事情变得更复杂?为什么这样做:
txtNumerator.Text =
txtNumerator.Text == "" ? "0" : txtNumerator.Text;
而不是这个:
if txtNumerator.Text="" {txtNumerator.Text="0";}
【问题讨论】:
标签: c#
假设您想将零或 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);
【讨论】:
class Foo : Bar { Foo( string txt ) : base( txt == "" ? "0" : txt ) } - for实例。您也可以编写静态成员来执行此操作,但在这种情况下使用 ?: 会更方便。
这是一个表达式,因此您可以直接在赋值或函数调用中使用结果,而无需复制使用它的上下文。这使得许多使用场景的读写更加清晰。例如:
int abs = (x >= 0) ? x : -x;
对
int abs;
if (x >= 0)
abs = x;
else
abs = -x;
【讨论】:
有许多标准指南说不要使用三元运算符。但是,您可能会同意,除了 goto 和 if 之外,所有语言功能都是不必要的。当有大量 if then else 时,我会使用它。
【讨论】:
在某些人看来,它使代码更具可读性,语言中的许多结构都是语法糖(想想 do..while、while..do 和 for(..)),并且在哪一天你选择适合你(和你的团队)的东西。
例如我认为上面的代码应该用扩展方法来实现:
txtNumerator.SetDefault("0");
【讨论】:
如果你使用 if-then 结构,你最终会在两个单独的块中对同一个变量进行两次赋值。三元形式只有一个赋值。因此,无需查看第二个块来验证两个块正在执行对同一变量的赋值。在这方面,我认为三元形式读起来更好。
另一方面,如果 C# 像 Ruby 一样工作并且 if 是一个表达式,那么您可以不使用三元运算符并在这种情况下使用 if-else:
txtNumerator.Text = if (txtNumerator.Text == "" ) "0"; else (txtNumerator.Text);
我更喜欢这样,因为这样可以删除 ?: 的不同语法。
【讨论】: