当我在我的代码上运行ReSharper时,例如:
if (some condition)
{
Some code...
}
Run Code Online (Sandbox Code Playgroud)
ReSharper给了我上面的警告(反转"if"声明以减少嵌套),并提出了以下更正:
if (!some condition) return;
Some code...
Run Code Online (Sandbox Code Playgroud)
我想明白为什么那样更好.我一直认为在方法中间使用"返回"有问题,有点像"goto".
在C,C++和C#使用条件时函数或循环语句中有可能使用继续或返回尽早声明,摆脱了其他的分支的if-else语句.例如:
while( loopCondition ) {
if( innerCondition ) {
//do some stuff
} else {
//do other stuff
}
}
Run Code Online (Sandbox Code Playgroud)
变
while( loopCondition ) {
if( innerCondition ) {
//do some stuff
continue;
}
//do other stuff
}
Run Code Online (Sandbox Code Playgroud)
和
void function() {
if( condition ) {
//do some stuff
} else {
//do other stuff
}
}
Run Code Online (Sandbox Code Playgroud)
变
void function() {
if( condition ) {
//do some stuff
return;
}
//do other …Run Code Online (Sandbox Code Playgroud) 在阅读MCSD学习指南时,我注意到作者说return在声明返回类型的方法中包含语句是非法的void.但是,当我创建以下方法时,Visual Studio没有在编辑器中标记它也没有编译失败:
private void ReturnNothing()
{
return;
}
Run Code Online (Sandbox Code Playgroud)
那么真正的答案是什么?这合法吗?