← 中文资源

简体中文版本

C# FormatException: 输入字符串的格式不正确

修复 C# 的 FormatException:Parse 与 string.Format 调用改用 TryParse、区域性感知解析并转义花括号。

阅读英文原文

症状

操作抛出 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。