StringBuilder AppendFormat 抛出 IndexOutOfRangeException

StringBuilder AppendFormat throws IndexOutOfRangeException

我在字符串中定义了一个模板:

public static string EntityClassBegginingTemplate =
    @"using System.Collections.Generic;

     //generated by the RuleDesigner
    public abstract class {0}Base : {1}
    {";

然后我尝试格式化一个字符串:

builder.AppendFormat(Templates.EntityClassBegginingTemplate, entityName, baseClass);

该行抛出异常:

IndexOutOfRangeException: Array index is out of range. System.String.FormatHelper (System.Text.StringBuilder result, IFormatProvider provider, System.String format, System.Object[] args) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/String.cs:1912) System.Text.StringBuilder.AppendFormat (IFormatProvider provider, System.String format, System.Object[] args) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Text/StringBuilder.cs:534) System.Text.StringBuilder.AppendFormat (System.String format, System.Object arg0, System.Object arg1) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Text/StringBuilder.cs:555)

我犯了什么错误?

我假设 class 模板的左大括号被解释为占位符。您需要转义任何要视为文字字符的花括号。

public static string EntityClassBegginingTemplate =
    @"using System.Collections.Generic;

     //generated by the RuleDesigner
    public abstract class {0}Base : {1}
    {"; <-- this is where the issue likely originated

正如 Ed Plunkett 指出的那样,您可以使用双大括号表示法转义大括号,{{as covered in the MSDN

Opening and closing braces are interpreted as starting and ending a format item. Consequently, you must use an escape sequence to display a literal opening brace or closing brace. Specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), or two closing braces ("}}") to display one closing brace ("}"). Braces in a format item are interpreted sequentially in the order they are encountered. Interpreting nested braces is not supported.