This question already has answers here:
String.Format exception when format string contains “{”
                                
                                    (5个答案)
                                
                        
                        
                            Escape curly brace '{' in String.Format [duplicate]
                                
                                    (1个答案)
                                
                        
                        
                            How to escape braces (curly brackets) in a format string in .NET
                                
                                    (10个答案)
                                
                        
                                去年关闭。
            
                    
我在下面简化了此方法来重现该问题,有人可以解释为什么引发系统格式异常吗?

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

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,然后在format部分中添加了一些C#MVC Razor。

最佳答案

谁能解释为什么引发系统格式异常?


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

{ <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> }");


老实说,这可能是一种更具可读性的解决方案。

关于c# - C#StringBuilder AppendFormat抛出System.FormatException ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53082109/

10-12 06:42