症状
操作抛出 FormatException: Input string was not in a correct format。它常出现在真实用户输入上,而硬编码值解析正常。
诊断
打印精确字符串并尝试安全解析:
Console.WriteLine($"[{input}]"); // exposes spaces / empty
if (!int.TryParse(input, out var n)) {
Console.WriteLine("not a number");
}
针对小数分隔符检查区域性。
修复
使用 TryParse 与显式区域性;转义花括号:
int.TryParse(input.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var n);
var json = string.Format(CultureInfo.InvariantCulture, "{{ \"n\": {0} }}", n);
验证
用出问题的字符串重跑;数值被解析或被干净地拒绝。补测试断言畸形输入产生校验错误而非未处理的 FormatException。