1

我快要爆炸了。我一直在寻找两个小时来解决这个问题的方法。我在 setTimer 方法中有一个 switch 语句。当我调试程序时,timerType 值会在方法运行时发生变化,但一旦退出,timerType 就会恢复为 null。这使我的 case 语句变得毫无用处,因为我需要在下次调用该方法时对其进行更改。我很想得到你的帮助,因为我确信它和往常一样简单:(。我尝试将其更改为 int 以查看它是否与 String 类型或其他什么有关。我有点菜鸟。请停止我不再挣扎(至少在这个特定问题上:))

public string timerType;



if (checkRoundChanged()) {
     SoundPlayer.Play();
     setTimer(timerType);
}

和方法

protected void setTimer(String timerType){
        switch (timerType) {
            case "ready":
                secLeft = readySec;
                minLeft = readyMin;
                timerType = "round";
                break;
            case "round":
                secLeft = roundSec;
                minLeft = roundMin;
                timerType = "rest";
                break;
            case "rest":
                secLeft = restSec;
                minLeft = restMin;
                timerType = "round";
                break;
            case "relax":
                secLeft = relaxSec;
                minLeft = relaxMin;
                timerType = "done";
                break;
            default:
                timerType = "ready";
                break;
        }

    }

谢谢!

4

1 回答 1

4

字符串是按值传递的,而不是按引用传递的。您可以返回新值:

protected string setTimer(String timerType){
    switch (timerType) {
        case "ready":
            secLeft = readySec;
            minLeft = readyMin;
            timerType = "round";
            break;
        case "round":
            secLeft = roundSec;
            minLeft = roundMin;
            timerType = "rest";
            break;
        case "rest":
            secLeft = restSec;
            minLeft = restMin;
            timerType = "round";
            break;
        case "relax":
            secLeft = relaxSec;
            minLeft = relaxMin;
            timerType = "done";
            break;
        default:
            timerType = "ready";
            break;
    }

    return timerType;
}

....

timerType =  setTimer(timerType);

或通过引用传递:

protected void setTimer(ref String timerType) {
   ...
   timerType = newValue;
   ...
}

setTimer(ref timerType);

这是一些推荐阅读

于 2012-10-28T13:38:31.693 回答