压缩代码:对一对中的任何元素执行相同的操作

发布于 2024-12-28 09:51:17 字数 966 浏览 2 评论 0原文

对于这种情况,有什么办法可以让代码更加紧凑吗?

// pseudocode
if (A == 1) {
    if (B == 2) {
        action1;
    }
    if (B == 3) {
        action2;
    }
}

if (B == 1) {
    if (A == 2) {
        action1;
    }
    if (A == 3) {
        action2;
    }
}

在 Objective-C/Objective-C++ 中?

再举一个例子:

if (((int)fixtureUserDataA == FIXTURE_FOOT_SENSOR || ((int)fixtureUserDataB == FIXTURE_FOOT_SENSOR ))) {

    // Hero foot sensors
    if (bodyA->GetUserData() != NULL) {
        CCSprite * sprite = (CCSprite*)bodyA->GetUserData();
        if (sprite.tag == TAG_HERO) {
            [Hero sharedInstance].numFootContacts++;             
        }
    }

    if (bodyB->GetUserData() != NULL) {
        CCSprite * sprite = (CCSprite*)bodyB->GetUserData();
        if (sprite.tag == TAG_HERO) {
            [Hero sharedInstance].numFootContacts++;             
        }
    }
}

是否可以只使用一个 if 或更清晰的结构?

Is there any way to make code more compact for this situation?

// pseudocode
if (A == 1) {
    if (B == 2) {
        action1;
    }
    if (B == 3) {
        action2;
    }
}

if (B == 1) {
    if (A == 2) {
        action1;
    }
    if (A == 3) {
        action2;
    }
}

in Objective-C/Objective-C++?

One more example:

if (((int)fixtureUserDataA == FIXTURE_FOOT_SENSOR || ((int)fixtureUserDataB == FIXTURE_FOOT_SENSOR ))) {

    // Hero foot sensors
    if (bodyA->GetUserData() != NULL) {
        CCSprite * sprite = (CCSprite*)bodyA->GetUserData();
        if (sprite.tag == TAG_HERO) {
            [Hero sharedInstance].numFootContacts++;             
        }
    }

    if (bodyB->GetUserData() != NULL) {
        CCSprite * sprite = (CCSprite*)bodyB->GetUserData();
        if (sprite.tag == TAG_HERO) {
            [Hero sharedInstance].numFootContacts++;             
        }
    }
}

Is it possible to use only one if or more clear construction?

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

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

发布评论

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

评论(2

八巷 2025-01-04 09:51:17

对于第二个例子:

checkBody(bodyA);
checkBody(bodyB);

void checkBody(Body* body)
{
    CCSprite * sprite = (CCSprite*)body->GetUserData();
        if (sprite.tag == TAG_HERO) {
            [Hero sharedInstance].numFootContacts++;             
        }
}

for 2nd example:

checkBody(bodyA);
checkBody(bodyB);

void checkBody(Body* body)
{
    CCSprite * sprite = (CCSprite*)body->GetUserData();
        if (sprite.tag == TAG_HERO) {
            [Hero sharedInstance].numFootContacts++;             
        }
}
尐籹人 2025-01-04 09:51:17
if (A == 1 || B == 1)
    if (A + B == 3)
        action1;
    else if (A + B == 4)
        action2;
if (A == 1 || B == 1)
    if (A + B == 3)
        action1;
    else if (A + B == 4)
        action2;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文