处理两个if条件的最简单方法

Simplest way to handle two if conditions

本文关键字:条件 最简单 方法 if 两个 处理      更新时间:2023-10-16

这与之前的问题相同,但我在描述问题时犯了很多错误。所以我再试一次。请原谅我的用词。这可能是错的。我是编程新手。

我有两个指针指向对象(我想)A和B。它们看起来像这样:

Class1* A = Blah->Method1();
Class2* B = A->Method2(); 

我必须在执行一些代码之前检查这些是否存在。以下是条件:

  • A和B同时存在:执行Action1和Action2
  • 存在,且其中一个为空:只执行Action1
  • 均为空:只执行Action1

这是我到目前为止的代码:

if (A){
/*some code here. B is created here */
    if (B){
        // Perform action1. Action1 always comes before Action2
        // Perform action2
    }
}
else{
    //Perform action1
}

这适用于4个案例中的3个。当A存在但B为空时,它会失败。

我该如何改进?(如果可能的话,同时将//Perform Action 1保持在最里面的if中。其他建议也欢迎。)

谢谢。

  • A和B同时存在:执行Action1和Action2
  • 存在,且其中一个为空:只执行Action1
  • 均为空:只执行Action1

所以,真的,你想:

action1();
if (a && b) {
  action2();
}

你的标准总是涉及调用action1;没有理由用if来保护它。如果同时找到ab,则调用action2

这个比上次清楚多了。这使得解决方案很简单:

bool doAction2 = false;
if (A) {
    /*some code here. B is created here */
    doAction2 = (B != null);
}
action1();
if (doAction2) {
    action2();
}