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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/963982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:21:34  来源:igfitidea点击:

Should I use return/continue statement instead of if-else?

c#c++c

提问by sharptooth

In C, C++ and C# when using a condition inside a function or loop statement it's possible to use a continueor returnstatement as early as possible and get rid of the elsebranch of an if-elsestatement. For example:

在 C、C++ 和 C# 中,当在函数或循环语句中使用条件时,可以尽早使用continuereturn语句并摆脱if-else语句的else分支。例如:

while( loopCondition ) {
    if( innerCondition ) {
        //do some stuff
    } else {
        //do other stuff
    }
}

becomes

变成

 while( loopCondition ) {
    if( innerCondition ) {
        //do some stuff
        continue;
    }
    //do other stuff
}

and

void function() {
    if( condition ) {
        //do some stuff
    } else {
        //do other stuff
    }
}

becomes

变成

void function() {
    if( condition ) {
        //do some stuff
        return;
    }
    //do other stuff
}

The "after" variant may be more readable if the if-else branches are long because this alteration eliminates indenting for the else branch.

如果 if-else 分支很长,“after”变体可能更具可读性,因为这种改变消除了 else 分支的缩进。

Is such using of return/continue a good idea? Are there any possible maintenance or readability problems?

使用 return/continue 是个好主意吗?是否存在任何可能的维护或可读性问题?

采纳答案by MSalters

The compiler will almost certainly generate the same code. Even if it didn't, the difference will be probably irrelevant. Hence, the relevant argument is certainly how people would read it.

编译器几乎肯定会生成相同的代码。即使没有,差异也可能无关紧要。因此,相关的论点当然是人们如何阅读它。

Therefore the question is how similar "//do some stuff" and "do other stuff" are. If they are conceptually similar, use if/else. If they're conceptually different, use continue/return.

因此,问题是“//做一些事情”和“做其他事情”有多相似。如果它们在概念上相似,请使用 if/else。如果它们在概念上不同,请使用 continue/return。

回答by Mehrdad Afshari

My personal approach of choosing one is that if the body of the ifpart is very short (3 or 4 lines maximum), it makes sense to use the return/continuevariant. If the body is long, it's harder to keep track of the control flow so I choose the elseversion.

我个人的选择方法是,如果if零件的主体非常短(最多 3 或 4 行),则使用return/continue变体是有意义的。如果主体很长,则很难跟踪控制流,因此我选择了else版本。

As a result, normally, this approach limits the usage of return/continuestyle to skip some data and avoid further processingrather than process this using one of the following methods(which is better suited by if/else).

因此,通常情况下,这种方法会限制return/continue样式的使用以跳过某些数据并避免进一步处理,而不是使用以下方法之一(更适合if/else)来处理它。

回答by Johan Kotlinski

It depends a little on how long the branches are. The use of return/continue that you describe is good if the initial ifcheck is short, and the body is long. If both ifand elseparts are long, I would extract them to separate functions.

这在一定程度上取决于树枝的长度。如果初始if检查很短并且主体很长,则您描述的 return/continue 的使用是好的。如果ifelse部分都很长,我会将它们提取到单独的函数中。

I recommend reading Code Complete, it discusses things like this a lot.

我推荐阅读 Code Complete,它讨论了很多这样的事情。

回答by Thorarin

I generally use the if-return method when jumping out of a method or loop because there is nothing to be done.

我一般在跳出方法或循环时使用 if-return 方法,因为没有什么可做的。

If the body is longer because substantial work is being done, I suggest using if-else and maybe using #regionto give blocks a sensible name and have them easily collapsable for people to study the control flow. That or make separate methods :)

如果由于正在进行大量工作而使主体更长,我建议使用 if-else 并可能使用#region为块提供一个合理的名称,并让它们易于折叠以供人们研究控制流。那个或制作单独的方法:)

回答by SO User

The code would be more readable if termination criteria are handled first. I always prefer, checking for conditions that require a break or return rather than those that would need lengthy code execution. I prefer:

如果首先处理终止条件,代码将更具可读性。我总是更喜欢检查需要中断或返回的条件,而不是需要冗长代码执行的条件。我更喜欢:

 if (termination condn) 
      return;
 // code 
 // code

to

if (success condn)
{
  // code
  // code
}
else
 return;

This makes reading and understanding the code easier.

这使得阅读和理解代码更容易。

回答by ChrisF

The glib answer is that it all depends.

油嘴滑舌的答案是这一切都取决于。

My general feeling is that if conditionis a rare, guard (e.g. check for null) or error condition then I tend to use returnor continue

我的一般感觉是,如果condition是罕见的、守卫(例如检查空值)或错误条件,那么我倾向于使用returncontinue

If it's an expected case then I tend to use your first approach.

如果这是预期的情况,那么我倾向于使用您的第一种方法。

Notice, however, that I said "tend". The boundary between these to conditions is vague and subject to change depending on the project and who I'm working with.

但是请注意,我说的是“倾向于”。这些条件之间的界限是模糊的,可能会根据项目和我合作的对象而变化。

回答by Sam Saffron

I usually prefer

我通常更喜欢

while( loopCondition ) {
    if( innerCondition ) {
        DoStuff();
    } else {
        DoOtherStuff(); 
    }
}

continue can be hard to follow if the length of DoStuff passed the 1-2 line threshold (and its fairly easy to miss the intention). This seems like a good opportunity to refactor the logic into some smaller methods.

如果 DoStuff 的长度超过 1-2 行阈值(并且很容易错过意图),则 continue 可能很难跟踪。这似乎是将逻辑重构为一些更小的方法的好机会。

回答by elmuerte

Do not sacrifice readability for premature optimization.

不要为了过早的优化而牺牲可读性。

For example:

例如:

void function() {
    if( condition ) {
        //do some stuff
    } else {
        //do other stuff
    }
}

is in most cases binary equivalent to

在大多数情况下是二进制等价于

void function() {
    if( condition ) {
        //do some stuff
        return;
    }
    //do other stuff
}

(i.e. the resulting code is probably the same). But the readability of the former is much better, because you can clearly see that the code will to either X or Y.

(即产生的代码可能是相同的)。但是前者的可读性要好得多,因为您可以清楚地看到代码将指向 X 或 Y。

回答by Steve Jessop

One possible maintenance issue is that if a function has multiple returns, then it is harder to stick a breakpoint or tracing at the return when debugging. This is only rarely an issue, but when you do miss a return point it's a pain. I don't think it matters so much for continue in loops, since the loop condition and the top of the loop are both still unique.

一个可能的维护问题是,如果一个函数有多个返回,那么在调试时很难在返回处设置断点或跟踪。这很少是一个问题,但是当您确实错过了返回点时,它会很痛苦。我认为循环中的 continue 没有那么重要,因为循环条件和循环顶部仍然是唯一的。

Aside from that: what everyone else says. Do what's most readable, which depends on the relative length, importance, and likelihood of "some stuff" and "other stuff". The shorter, more trivial, and more unlikely a case is, the less disturbing it is for it to have special-case control flow.

除此之外:其他人说什么。做最易读的事情,这取决于“某些东西”和“其他东西”的相对长度、重要性和可能性。一个案例越短、越琐碎、越不可能,拥有特殊案例控制流的干扰就越小。

回答by Joakim Elofsson

as other people said, only use return/continue if things are short.

正如其他人所说,只有在事情很短的情况下才使用返回/继续。

Personally i only use continue if it is possible to write on one line like:

就个人而言,如果可以在一行上写,我只使用 continue ,例如:

while( loopCondition ) {
    if( innerCondition ) continue;

    //do other stuff
}

If it's not possible to write it like this without code getting ugly, then if / else.

如果不可能像这样编写它而不会使代码变得丑陋,那么 if / else.