相关疑难解决方法(0)

反转"if"语句以减少嵌套

当我在我的代码上运行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# resharper

257
推荐指数
17
解决办法
11万
查看次数

我应该使用return/continue语句而不是if-else吗?

在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)

c c# c++

28
推荐指数
7
解决办法
2万
查看次数

你能在声明为void的C#方法中使用"return"语句吗?

在阅读MCSD学习指南时,我注意到作者说return在声明返回类型的方法中包含语句是非法的void.但是,当我创建以下方法时,Visual Studio没有在编辑器中标记它也没有编译失败:

private void ReturnNothing()
{
    return;
}
Run Code Online (Sandbox Code Playgroud)

那么真正的答案是什么?这合法吗?

c# return void

2
推荐指数
1
解决办法
4048
查看次数

标签 统计

c# ×3

c ×1

c++ ×1

resharper ×1

return ×1

void ×1