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

发布于 2024-07-13 21:32:57 字数 460 浏览 8 评论 0原文

我有几个方法根据它们的成功返回一个 bool ,在 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
}

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

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

谢谢。

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

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() ?

//&& 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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

吹梦到西洲 2024-07-20 21:32:57

我会指出您可以使用 & 操作符(与&&相对)来保证即使左侧为false,如果由于某种原因在未来你希望避免短路。

| 则相反。 运算符,即使左侧条件的计算结果为true,右侧条件也将被计算。

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.

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.

z祗昰~ 2024-07-20 21:32:57

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

干净得多

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

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

例如,写:比写:

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

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!

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
}
深爱不及久伴 2024-07-20 21:32:57

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

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

,或者你可以一起去

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

所以我想你的问题的答案恕我直言是,不,虽然行为是你所描述的,但你的意思并不完全清楚。

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

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.

只为一人 2024-07-20 21:32:57

仅当这些方法是纯(无副作用)函数时我才会推荐它。

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

爺獨霸怡葒院 2024-07-20 21:32:57

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

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

如果短路表达式有某种副作用,严格从维护角度来看,分隔语句可能更具可读性。

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

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.

蓝礼 2024-07-20 21:32:57

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

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

段念尘 2024-07-20 21:32:57

应该没有什么问题。

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

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

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

但是,我总是观察到您的代码将按预期运行,所以这可能是没有必要的。

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.

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

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.

迷你仙 2024-07-20 21:32:57

没什么错。

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

Nothin' wrong.

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

‘画卷フ 2024-07-20 21:32:57

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

我的准则是:

  • 如果方法名称很短,并且方法名称不是太多,那么就很好。
  • 如果 if 语句内有太多语句/方法调用,则您很可能正在比较多个“一组”事物。 打破这些“集合”并引入临时变量。
  • “太多”是主观的,但通常超过 3 个左右。
  • 当我说“方法名称很短”时,我指的不仅仅是名称,还有它们所采用的参数。 基本上是某人阅读它所需的努力。 例如,if( Open(host) )if( WeCouldConnectToTheServer ) 短。 所有这些项目的总大小就是它的大小。

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

My guidelines are:

  • 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 if statement, 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.
驱逐舰岛风号 2024-07-20 21:32:57

就我个人而言,我认为

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

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

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文