首页 > 解决方案 > 将 2 个转换为 int 的数组字符串加在一起时出现我不明白的错误

问题描述

这是我发现的错误:FormatException:输入字符串的格式不正确。System.Number.StringToNumber (System.String str, System.Globalization.NumberStyles options, System.Number+NumberBuffer& number, System.Globalization.NumberFormatInfo info, System.Boolean parseDecimal) (在 <437ba245d8404784b9fbab9b439ac908>:0)

编辑:参数是 5 4,很长的背景故事,但拆分是将 5 5 变成 wordX = 5,wordY = 4,然后将它们加在一起。

string[] numbers = argument.Split(new[] { " " }, System.StringSplitOptions.None);

string wordX = numbers[0];
string wordY = numbers[1];

int numberX = Int32.Parse(wordX);
int numberY = Int32.Parse(wordY);

Debug.Log(numberX + numberY);

标签: c#unity3d

解决方案


我相信您的字符串值wordX并且wordY无法解析为 int。我建议您改用 TryParse 来避免异常。

if(int.TryParse(wordX, out int numberX) &&
   int.TryParse(wordY, out int numberY))
{
   Debug.Log(numberX + numberY);
}
else
{
   // this will let you see why it was failing
   Debug.Log($"Error Parsing: wordX is [{wordX ?? "null"}] and wordY is [{wordY ?? "null"}]");
}

推荐阅读