C# StringBuilder AppendFormat 抛出 System.FormatException

C# StringBuilder AppendFormat throwing System.FormatException

我有下面这个方法,我已经简化以重现问题,谁能解释为什么会抛出系统格式异常?

我曾尝试将 @ 添加到格式字符串的开头,以防转义字符出现问题,但没有帮助。

private void doThing(StringBuilder builder, string inPrimaryKey) {
    // At this point the builder.ToString() results in "            <div  class="v-group width-100 shadowed OrderPanel"
    // and inPrimaryKey is "OrderId"

    // Throws System.FormatException with the detail "Input string was not in a correct format."
    builder.AppendFormat(@" @if (Model.{0} > 0) { <text>StateNonEditable</text> } else { <text>StateEditable</text> }", inPrimaryKey);
}

一些背景知识,我们正在使用此代码生成一个用于 Web 应用程序的 cshtml 页面,因此 stringbuilder 最初包含一些 html 然后我们添加一些 C#格式部分中的 MVC Razor。

can anyone explain why the system format exception is thrown?

是:您的格式字符串包括:

{ <text>StateNonEditable</text> }

这不是有效的格式项。您需要将 不是 的大括号加倍以转义为格式项的一部分:

builder.AppendFormat(
    " @if (Model.{0} > 0) {{ <text>StateNonEditable</text> }} else {{ <text>StateEditable</text> }}",
    inPrimaryKey);

或者,只需调用 AppendFormat 一次,然后调用 Append 一次:

builder.AppendFormat(" @if (Model.{0} > 0 ", inPrimaryKey)
       .Append("{ <text>StateNonEditable</text> } else { <text>StateEditable</text> }");

老实说,这可能是一个更易读的解决方案。