简体   繁体   English

Resharper冗余'其他'真的多余?

[英]Resharper redundant 'else' really redundant?

Resharper is telling me that the 'else' in this code is redundant: Resharper告诉我这段代码中的'else'是多余的:

if(a)
{
   //Do Something
}
else if(b)
{
   //Do Something
}

The else does not seem redundant because the else keeps b from being evaluated if a is true. else似乎并不多余,因为如果a为真, else会阻止b被评估。 The extra overhead is small if b is a variable, but b could also be an expression. 如果b是变量,则额外开销很小,但b也可以是表达式。

Is this correct? 这个对吗?

It's redundant if you have a some sort of break , continue , return , or throw statement (or even a goto ) inside the first if -block that always causes execution to branch outside the current block: 如果你在第一个if -block中有一些breakcontinuereturnthrow语句(甚至是goto )总是会导致执行在当前块之外分支,那就多余了:

if(a)
{
    return 0;
}
else if(b)
{
    return 1;
}

In this case, if the code enters the first block, there's no way it will enter the second block, so it's equivalent to: 在这种情况下,如果代码进入第一个块,则无法进入第二个块,因此它相当于:

if(a)
{
    return 0;
}
if(b)
{
    return 1;
}

You are right in this case, but this is the reason I think they had it to begin with: 在这种情况下你是对的,但这就是我认为他们开始时的原因:

Certain if-else conditions can have their else clause removed. 某些if-else条件可以删除其else子句。 Consider the following method: 请考虑以下方法:

public int Sign(double d)
{
    if (d > 0.0)
        return 1;
    else
        return -1;
}

In the above, the else statement can be safely removed because its if clause returns from the method. 在上面,可以安全地删除else语句,因为它的if子句从方法返回。 Thus, even without the else, there's no way you'll be able to proceed past the if clause body. 因此,即使没有其他,你也无法通过if子句体。

It doesn't appear redundant to me. 这对我来说似乎并不多余。 Removing the else would result in different program flow if both a and b are true. 如果ab都为真,则删除else将导致不同的程序流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM