C# 哪个更好地在嵌套的 If 中应用两个条件或使用单个和 And?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/320480/
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-03 23:05:55  来源:igfitidea点击:

Which is better apply two conditions in nested If or using single with And?

c#vb.net

提问by Nakul Chaudhary

Nested If or single if with And operator, which is better approach?
Single If with And

嵌套 If 或单个 if 与 And 运算符,哪种方法更好?
单如果与和

if (txtPackage.Text != string.Empty && txtPackage.Text == "abc")
{
   //
}

Nested If

嵌套如果

if (txtPackage.Text != string.Empty)
{ 
  if (txtPackage.Text == "abc")
  {
     //
  }
}

采纳答案by itsmatt

Are you going to do something different in the 'nested if' example if, in fact, txtPackage.Text isn't empty but contains something other than "abc"?

如果实际上 txtPackage.Text 不为空但包含除“abc”以外的其他内容,您是否打算在“嵌套 if”示例中做一些不同的事情?

If you aren't, I'd ask why are you checking for string.empty at all?

如果不是,我会问你为什么要检查 string.empty ?

You could just write:

你可以写:

if (txtPackage.Text == "abc")
{

//

}

and be done with it.

并完成它。

Totally depends upon what you want to do in the end.

完全取决于你最终想做什么。

回答by The Archetypal Paul

You really need to define what you mean by "better".

你真的需要定义你所说的“更好”是什么意思。

My style is to use one if and an AND if, like in your example, I'm testing the same thing for two different values.

我的风格是使用一个 if 和一个 AND if,就像在你的例子中一样,我正在为两个不同的值测试相同的东西。

If the two tests are conceptually different, I'll probably nest them

如果这两个测试在概念上不同,我可能会将它们嵌套

if (!user_option.work_offline) {
    if (no_current_connection) {
        start_connection()
    }
}

回答by ZombieSheep

+1 to itsmatt

+1 到它的马特

On the original question, I personally avoid nested ifs wherever possible, otherwise I'd end up with lots of arrow code.

在最初的问题上,我个人尽可能避免嵌套 if,否则我最终会得到很多箭头代码。

There are, however, exceptions to this mini-rule. If there is going to be different behaviour for each of the conditional outcomes, then nested ifs maybe an answer. You need to carefully consider the impact of nesting so you don't write difficult to read (and therefore maintain) code.

然而,这个小规则也有例外。如果每个条件结果都有不同的行为,那么嵌套 ifs可能是一个答案。您需要仔细考虑嵌套的影响,以免编写难以阅读(因此难以维护)的代码。

回答by Timothy Khouri

I wasn't going to chime in, but seeing that some answers here seem to be about "I like my code to looklike this"... I feel that I should say something :)

我不打算插话,但看到这里的一些答案似乎是关于“我喜欢我的代码看起来像这样”......我觉得我应该说点什么:)

"Better" means the code will execute faster, or it's more readable / extendable. You wouldwant to nest your if's in the case that you would possibly have multiple checks that all have a common requirement.

“更好”意味着代码将执行得更快,或者更具可读性/可扩展性。如果您可能有多个检查,所有检查都有一个共同的要求,则您可能希望嵌套您的 if。

Example:

例子:

if (myThingy != null)
{
    if (myThingy.Text = "Hello") ...

    if (myThingy.SomethingElse = 123) ...
}

EDIT: It also needs to be said that nesting your IF's requires more CPU cycles (and is therefore "slower") than a single IF. On top of that, the order of your conditions can greatly increase performance.

编辑:还需要说明的是,与单个 IF 相比,嵌套 IF 需要更多的 CPU 周期(因此“更慢”)。最重要的是,条件的顺序可以大大提高性能。

Exapmle again:

再举例:

if (somethingQuick() && somethingThatTakesASecondToCalculate()) ...

is a LOT faster (of course) than

比(当然)快很多

if (somethingThatTakesASecondToCalculate() && somethingQuick()) ...

Because if the first part of the IF fails, the second part won't even be executed, thus saving time.

因为如果IF的第一部分失败,第二部分甚至不会被执行,从而节省了时间。

回答by Timothy Khouri

I prefer using conditional AND/OR operators when needed, instead of nested ifs. Looks less messy and makes for less lines of code.

我更喜欢在需要时使用条件 AND/OR 运算符,而不是嵌套的 if。看起来不那么凌乱,代码行也更少。

if (thisIsTrue) {
if (thisIsTrueToo) doStuff();
}

is essentally same as:

本质上是一样的:

if (thisIsTrue && thisIsTrueToo) doStuff();

if thisIsTrue is false, the second condition is not evaluated. Works also for || for conditional OR.

如果 thisIsTrue 为假,则不评估第二个条件。也适用于 || 用于条件 OR。

回答by dragonjujo

I think it depends on how you want it to flow, if you are only executing on true, true (or any other singularity) then one if statement is all you need.

我认为这取决于你希望它如何流动,如果你只在真、真(或任何其他奇点)上执行,那么你只需要一个 if 语句。

回答by codeape

I feel that it is better to avoid nested ifs.

我觉得最好避免嵌套 ifs。

Sometimes, I even duplicate simple tests to avoid a nesting level.

有时,我什至复制简单的测试以避免嵌套级别。

Example (python):

示例(蟒蛇):

# I prefer:
if a and b:
    foo()
elif a and not b:
    bar()
elif not a and b:
    foobar()
elif not a and not b:
    baz()

# Instead of:
if a:
    if b:
        foo()
    else:
        bar()
else:
    if b:
        foobar()
    else:
        baz()

Sometimes it is more natural to have an else-clause as the last part. In those cases, I typically assert the conditions of the else clause. Example:

有时将 else 子句作为最后一部分更自然。在这些情况下,我通常会断言 else 子句的条件。例子:

if a and b:
    foo()
elif a and not b:
    bar()
elif not a and b:
    foobar()
elif not a and not b:
    baz()
else:
    assert not a and not b
    baz()

回答by shrads

It depends on what exactly you want to achieve. It's a logical question rather than a programming query. If you have a dependent condition i.e. If the first is TRUE and then test the second condition; if second TRUE then do something , if FALSE do something, in this case you need to use a nested if. But you need the state of both the conditions to do something then you can go with the operators.

这取决于您究竟想要达到什么目的。这是一个逻辑问题,而不是一个编程查询。如果你有一个依赖条件,即如果第一个条件为真,然后测试第二个条件;如果第二个 TRUE 然后做某事,如果 FALSE 做某事,在这种情况下,您需要使用嵌套的 if。但是您需要两个条件的状态才能做某事,然后您可以使用运算符。

回答by J.T. Hurley

In my opinion, you should use the style that makes the most sense for what you're testing for. If the two are closely coupled, you could test for both on the same line without a loss of clarity. Particularly easy when the program permits "if x == (1 OR 2)" constructions.

在我看来,您应该使用对您正在测试的内容最有意义的样式。如果两者紧密耦合,您可以在同一条线上测试两者,而不会失去清晰度。当程序允许“if x == (1 OR 2)”结构时特别容易。

On the other hand, if the two tests are disjointed, I'd prefer to separate them to make the logic more explicit.

另一方面,如果两个测试脱节,我更愿意将它们分开以使逻辑更加明确。

回答by vicki

no one has mentioned maintaining that code. Which is easier to debug?

没有人提到维护该代码。哪个更容易调试?

if this fails:

如果失败:

if (thisIsTrue && thisIsTrueToo)
    doStuff();

you know one of these two statements failed, but not which one.

您知道这两个语句中的一个失败了,但不知道是哪一个。

if this fails:

如果失败:

if (thisIsTrue) {
  if (thisIsTrueToo)
    doStuff();
}

your exception tells you the line number. I say go for easy maintenance, as you are likely not going to be on this code forever.

您的异常告诉您行号。我说的是为了便于维护,因为您可能不会永远使用此代码。