在 if() 中调用方法 - C#

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

Calling methods inside if() - C#

c#language-featuresshort-circuiting

提问by roman m

I have a couple of methods that return a bool depending on their success, is there anything wrong with calling those methods inside of the IF() ?

我有几个方法根据它们的成功返回一个布尔值,在 IF() 内部调用这些方法有什么问题吗?

//&& makes sure that Method2() will only get called if Method1() returned true, use & to call both methods
if(Method1() && Method2())
{
    // do stuff if both methods returned TRUE
}

Method2() doesn't need to fire if Method1() returns FALSE.

如果 Method1() 返回 FALSE,则 Method2() 不需要触发。

Let me know there's any problem with the code above.

让我知道上面的代码有任何问题。

thank you.

谢谢你。

EDIT:since there was nothing wrong with the code, I'll accept the most informative answer ... added the comment to solve the "newbie & &&" issue

编辑:由于代码没有任何问题,我会接受最有用的答案......添加了解决“新手&&&”问题的评论

采纳答案by John Rasch

I'll throw in that you can use the & operator(as opposed to &&) to guarantee that both methods are called even if the left-hand side is false, if for some reason in the future you wish to avoid short-circuiting.

我要强调的是,如果将来出于某种原因您希望避免短路,您可以使用& operator(而不是&&)来保证即使左侧是 也调用这两种方法false

The inverse works for the | operator, where even if the left-hand condition evaluates to true, the right-hand condition will be evaluated as well.

反之亦然| operator,即使左边的条件计算为true,右边的条件也将被计算。

回答by Jason Punyon

Nothin' wrong.

没什么错。

Actually...I wouldn't name them Method1 and Method2. Something more descriptive. Maybe passive sounding too (like StuffHasHappened or DataHasLoaded)

实际上......我不会将它们命名为 Method1 和 Method2。更具描述性的东西。也可能是被动的声音(比如 StuffHasHappened 或 DataHasLoaded)

回答by chills42

No, there is nothing wrong with method calls in the if condition. Actually, that can be a great way to make your code more readable!

不,if 条件中的方法调用没有任何问题。实际上,这可能是使您的代码更具可读性的好方法!

For instance, it's a lot cleaner to write:

例如,编写以下代码要干净得多:

private bool AllActive()
{
    return x.IsActive && y.IsActive && z.IsActive;
}

if(AllActive())
{
    //do stuff
}

than:

比:

if(x.IsActive && y.IsActive && z.IsActive)
{
    //do stuff
}

回答by n8wrl

As useful as they are, sequence points can be confusing. Unless you really understand that, it is not clear that Method2() might not get called at all. If on the other hand you needed BOTH methods to be called AND they had to return true, what would you write? You could go with

尽管它们很有用,但序列点可能会令人困惑。除非您真正理解这一点,否则可能根本不会调用 Method2() 并不清楚。另一方面,如果您需要调用 BOTH 方法并且它们必须返回 true,您会写什么?你可以去

bool result1 = Method1();
bool result2 = Method2();
if (result1 && result2)
{
}

or you could go with

或者你可以去

if (Method1())
    if (Method2())
    {
    }

So I guess the answer to you question IMHO is, no, it's not exactly clear what you mean even though the behavior will be what you describe.

所以我想你的问题恕我直言的答案是,不,即使行为将是你所描述的,你的意思也不是很清楚。

回答by Chris Ballance

Looks good to me, multiple clauses in the if() block will short circuit if an earlier condition fails.

对我来说看起来不错,如果较早的条件失败,if() 块中的多个子句将短路。

回答by TJB

There shouldn't be any problem.

应该没有什么问题。

The normal behavior is that Method1() will execute, and if that returns true Method2() will execute, and depending on what Method2() returns, you may / may not enter the if() statement.

正常行为是 Method1() 将执行,如果返回 true Method2() 将执行,并且取决于 Method2() 返回的内容,您可能/可能不输入 if() 语句。

Now, this assumesthat the compiler generates code that executes that way. If you want to be absolutely surethat Method2() doesn't execute unless Method1() returns true you could write it like this

现在,这假设编译器生成以这种方式执行的代码。如果你想绝对确定Method2() 不会执行,除非 Method1() 返回 true 你可以这样写

if( Method1() )
{
  if( Method2() )
  {
    // do stuff if both methods returned TRUE 
  }
}

But, I've always observed that your code will run as expected, so this is probably not necessary.

但是,我一直观察到您的代码会按预期运行,因此这可能没有必要。

回答by Rauhotz

I would only recommend it if the methods are pure (side-effect-free) functions.

如果方法是纯(无副作用)函数,我只会推荐它。

回答by Erik Funkenbusch

While, as everyone says, there's nothing "wrong" with doing things this way, and in many cases you're doing precisely what the language was designed for.

虽然,正如每个人所说的那样,以这种方式做事并没有“错”,而且在许多情况下,您所做的正是该语言的设计目的。

Bear in mind, however, that for maintainabilities sake, if Method2 has side effects (that is, it changes somethings state) it may not be obvious that this function is not being called (a good programmer will usually know, but even good programmers sometimes have brain farts).

但是请记住,为了可维护性,如果 Method2 有副作用(即,它改变了某些状态),则该函数未被调用可能并不明显(优秀的程序员通常会知道,但即使是优秀的程序员有时也会知道)有脑放屁)。

If the short circuited expression has some kind of side effect, it may be more readable to seperate the statements, strictly from a maintenance perspective.

如果短路表达式有某种副作用,则严格从维护的角度来看,将语句分开可能更易读。

回答by gillonba

Personally, I would consider

就个人而言,我会考虑

if(Method1() && Method2())
{
    // do stuff if both methods returned TRUE
}

to be a bad practice. Yes, it works in the current environment, but so does

是一个不好的做法。是的,它适用于当前环境,但也适用

if(Method1())
{
  if (Method2())
  {
    // do stuff if both methods returned TRUE
  }
}

But will it work in ALL environments? Will future, possibly non-Microsoft, C# compilers work this way? What if your next job involves another language where both methods will always be called? I wouldn't rely on that particular construct not because it's wrong, but because it doesn't solve any serious problem, and it may become wrong in the future

但它会在所有环境中工作吗?未来的,可能是非微软的,C# 编译器会以这种方式工作吗?如果您的下一份工作涉及另一种语言,其中两种方法都将始终被调用,该怎么办?我不会依赖那个特定的构造,不是因为它是错误的,而是因为它不能解决任何严重的问题,而且将来可能会出错

回答by Orion Edwards

Looks good to me, but there are some caveats... This is NOT the kind of thing where blanket rules apply.

对我来说看起来不错,但有一些警告......这不是一揽子规则适用的那种事情。

My guidelinesare:

我的指导方针是:

  • If the method names are short, and there are not too many of them, then it's all good.
  • If you have too many statements/method calls inside the ifstatement, you most likely are comparing more than one "set" of things. Break those "sets" out and introduce temporary variables.
  • "Too many" is subjective, but usually more than around 3
  • When I say "method names are short" I'm talking not just about the names, but the parameters they take as well. Basically the effort required for someone to read it. For example if( Open(host) )is shorter than if( WeCouldConnectToTheServer ). The total size of all these items is what it comes down to.
  • 如果方法名很短,而且数量不多,那么一切都很好。
  • 如果语句中有太多语句/方法调用if,则很可能要比较多个“一组”事物。打破这些“集合”并引入临时变量。
  • “太多”是主观的,但通常超过 3
  • 当我说“方法名很短”时,我说的不仅仅是名称,还有它们采用的参数。基本上是某人阅读它所需的努力。例如if( Open(host) )短于if( WeCouldConnectToTheServer ). 所有这些项目的总大小就是它的总和。