Skip to main content
 首页 » 编程设计

c#之一旦方法完成,我的变量就会不断切换回来

2024年02月20日11lvdongjie

我要爆炸了。我一直在寻找解决此问题的方法两个小时。我在 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; 
        } 
 
    } 

谢谢!

请您参考如下方法:

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

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

这是一些 recommended reading .