将字符串转换为 int 然后再转换回字符串

Nai*_*aik 1 c# unity-game-engine

我试图将我的字符串变量转换为整数以向它添加一个值(+1),但我得到的结果是:

1111
Run Code Online (Sandbox Code Playgroud)

事实上,当我将它重新转换为字符串时,我总共应该得到 4 个。

我究竟做错了什么?

public string str_Val = "1";

void Update () {
if (str_Val  != "5") {
      str_Val  = int.Parse (str_Val + 1).ToString ();
   }
}
Run Code Online (Sandbox Code Playgroud)

Ath*_*ras 6

这完全取决于操作的优先级:

int.Parse (str_Val + 1)
Run Code Online (Sandbox Code Playgroud)

另外,在上述第一加法行发生str_Val + 1outputing 11111111等。

然后解析发生更改"11"11

然后到字符串发生更改11"11"

因此,将您的代码更改为

str_Val  = (int.Parse(str_Val)+1).ToString();
Run Code Online (Sandbox Code Playgroud)

这将首先将字符串转换为 int,然后添加两个整数,最后再次将整数转换为字符串。