我发现很难找到这个问题。
else语句会对下面的代码产生任何影响吗?
public string Test()
{
if (statement) return "a";
else return "b";
}
在这种情况下有什么好的做法?
答案 0 :(得分:4)
不,在这种情况下它不会有任何区别,因为如果if语句为真,它将返回并且永远不会转到return "b";
行而不管if。
在这种情况下,我通常会省略其他内容,但我不知道大多数人在这种情况下是否会这样做。
答案 1 :(得分:2)
else 可能是不必要的,但我个人认为,添加一些可读性并平衡 if 逻辑是一个很小的代价。
答案 2 :(得分:2)
我通常更喜欢没有else
的变体。虽然它们在功能上等效,但else
版本有时会导致大量缩进。
public string Test() {
if (statement)
return "a";
return "b";
}
对于像这样的简单情况,这两种变体都没有什么问题,但是它与(例如)函数开头的四次检查(伪代码)形成鲜明对比:
define fn():
if error condition 1:
handle error 1
else:
if error condition 2:
handle error 2
else:
if error condition 3:
handle error 3
else:
if error condition 4:
handle error 4
else:
do something
而不是:
define fn():
if error condition 1:
handle error 1
return
if error condition 2:
handle error 2
return
if error condition 3:
handle error 3
return
if error condition 4:
handle error 4
return
do something
在我看来,后者是“更清洁”的代码。
答案 3 :(得分:2)
没有区别,编译器可能会在两种情况下都发出相同的信号。另外,对于像您的示例那样的小型支票,您始终可以使用以下(conditional operator):
public string Test()
{
return statement ? "a" : "b";
}
答案 4 :(得分:2)
关于制作最清晰代码的所有内容。
就我个人而言,我觉得在大多数情况下,还原剂使代码更清晰,但其他人可能会有不同的感受。
无论哪种方式,我个人会为你的if / else使用括号,但是其他人可能觉得这会使代码太冗长。
public string Test()
{
if (statement)
{
return "a";
}
else
{
return "b";
}
}
或
public string Test()
{
if (statement)
{
return "a";
}
return "b";
}
答案 5 :(得分:2)
没有区别,但我在这种特殊情况下的偏好是:
public string Test() {
return statement ? "a" : "b";
}
在任何情况下,我都不会保留else语句,但这主要是因为我使用了ReSharper,它使else语句变暗,而且我对这类事情有点强迫症。
答案 6 :(得分:2)
没有区别,事实上他们都编译成同一个IL:
public bool GetValue(bool input)
{
if (input) return true;
return false;
}
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0005
IL_0003: ldc.i4.1
IL_0004: ret
IL_0005: ldc.i4.0
IL_0006: ret
和
public bool GetValue2(bool input)
{
if (input)
return true;
else
return false;
}
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0005
IL_0003: ldc.i4.1
IL_0004: ret
IL_0005: ldc.i4.0
IL_0006: ret
答案 7 :(得分:1)
它不会有任何区别。你应该写下你喜欢的方式(ofc。坚持一种模式);)
答案 8 :(得分:0)
没有...在代码中没有else会执行同样的事情
答案 9 :(得分:0)
没有。它们在逻辑上是一样的。
if(xx) return; else return;
if(xx) return;
return;