使用 switch 语句进行加法和减法

Using switch statement for both addition and substraction

我的程序中有几个很长的 switch case,我需要在 switch case 中同时做减法和加法。我想尽可能地编写干净的代码。我不想每次都手动复制粘贴并将 + 符号更改为 - 符号。我怎样才能做到这一点。

这是示例;

private void SetWorkerBonus()
{
    switch (currentWorkerType)
    {
        case WorkerType.Gatherer:
            outputValue += currentWorkerCount * 1.1f;
            break;
        case WorkerType.Hunter:
            defenseAmount += currentWorkerCount * 1.06f;
            break;
        case WorkerType.Cook:
            foodAmount += currentWorkerCount * 1.03f;
            break;
        case WorkerType.Warrior:
            attackAmount += currentWorkerCount * 1.05f;
            break;
    }
}

我希望我的方法是相同的,除了用 + 代替 - 标志。 为了进一步说明,当我为 class 设置奖金并更改工人类型时,我想减去我给予的奖金然后给予新类型的奖金。

如果解决方案是 with/out switch 语句并不重要。我只是想要一个明确的解决方案。

您只需将布尔标志传递给您的 SetWorkerBonus。如果为真则要加,如果为假则要减。现在使用此标志将整数变量初始化为 1 或 -1 并使用此整数乘以围绕 currentWorkerCount

进行的计算
private void SetWorkerBonus(bool flagToAddOrSubtract)
{
    int multiplier = (flagToAddOrSubtract ? 1 : -1);
    switch (currentWorkerType)
    {
      
        case WorkerType.Gatherer:
            outputValue += ((currentWorkerCount * 1.1f) * multiplier);
            break;
        case WorkerType.Hunter:
            defenseAmount += ((currentWorkerCount * 1.06f) * multiplier);
            break;
        case WorkerType.Cook:
            foodAmount += ((currentWorkerCount * 1.03f) * multiplier);
            break;
        case WorkerType.Warrior:
            attackAmount += ((currentWorkerCount * 1.05f) * multiplier);
            break;
    }
}

在函数 SetWorkerBonus 中传入一个布尔变量作为参数,并在 switch 语句中基于三元运算符执行 + 或 -

private void SetWorkerBonus(boolean isAdd)
{
    switch (currentWorkerType)
    {
        case WorkerType.Gatherer:
            outputValue = isAdd ? outputValue + currentWorkerCount * 1.1f : outputValue - currentWorkerCount * 1.1f
            break;
        case WorkerType.Hunter:
            defenseAmount = isAdd ? defenseAmount + currentWorkerCount * 1.06f : defenseAmount - currentWorkerCount * 1.06f;
            break;
        case WorkerType.Cook:
            foodAmount = isAdd ? foodAmount + currentWorkerCount * 1.03f : foodAmount - currentWorkerCount * 1.03f;
            break;
        case WorkerType.Warrior:
            attackAmount = isAdd ? attackAmount + currentWorkerCount * 1.05f : attackAmount - currentWorkerCount * 1.05f;
            break;
    }
}