【问题标题】:Odd System.Format Exception [duplicate]奇怪的 System.Format 异常 [重复]
【发布时间】:2019-07-24 00:37:50
【问题描述】:

我只是想为我的单元测试构建一个 json 字符串,但意外地以下代码返回了系统格式异常。错误消息表明它正在尝试解析日期,这对我来说很奇怪。我不是要解析日期。

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(GetJson());
        Console.ReadKey();
    }

    static string GetJson(string dateStr = "", string lta = "5.25")
    {
        return String.Format("[{\"dateBooking\":\"{0}\",\"lta\":\"{1}\"}]", dateStr, lta);
    }
} 

它可以很容易地复制,但我正在添加异常详细信息:

“'System.FormatException' 类型的未处理异常发生在 mscorlib.dll

附加信息:输入字符串的格式不正确。"

【问题讨论】:

  • 添加异常详情

标签: c# string.format


【解决方案1】:

您需要将{{{}}} 一起转义,因为String.Format 将搜索类似{0:000} 的参数,但会找到{"dateBooking ... },这不是有效的参数格式。这就是引发 FormatException 的原因。

return String.Format("[{{\"dateBooking\":\"{0}\",\"lta\":\"{1}\"}}]", dateStr, lta);

【讨论】:

  • 酷,成功了,我会在 6 分钟内将其标记为答案。但是,我认为异常消息具有误导性。
  • 异常消息是Input string was not in a correct format.,因为您提供了一个格式字符串作为第一个参数,所以它需要以正确的方式格式化。
  • 我个人使用 Resharper,它告诉我以下信息:Format item index must be a number starting 0 without any leading or trailing whitespaces 当您经常使用 C# 时,我建议您安装 Resharper(它不是免费的,但它是值得的)
  • 在错误信息的详细信息中,它还提到了与日期时间完全无关的转换错误。我已经在使用 ReSharper,只是错过了那个警告。
  • 错误本身没有提到任何DateTime 错误。您是否正在查看“故障排除提示”?因为这些只是向FormatException显示一般错误处理提示
猜你喜欢
  • 1970-01-01
  • 2019-12-30
  • 2011-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多