c# - 将 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);
解决方案
我相信您的字符串值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"}]");
}
推荐阅读
- .htaccess - htaccess 太多重定向
- sql - 选择上一个动作之后的第一个动作实例
- typescript - 如何将导出的 keyof 转换为字符串类型
- javascript - 打开 Chrome Devtools 重新加载 Hulu 会导致奇怪的行为
- postgresql - Peewee SQL - 如何在查询中使用 Python any() 和 all() 运算符
- python-3.x - 与直接在笔记本中的 colab 上运行相同的代码相比,在 colab 中运行 python 脚本非常慢
- aws-lambda - AWS HTTP API Gateway:阶段变量
- python - ModuleNotFoundError:没有名为“PIL”的模块
- javascript - React.js useRef钩子没有返回预期的对象
- go - 为什么 Go 经常将字符串的数据存储在未对齐的地址