【问题标题】:StringBuilder AppendFormat throws IndexOutOfRangeExceptionStringBuilder AppendFormat 抛出 IndexOutOfRangeException
【发布时间】:2016-09-19 18:29:37
【问题描述】:

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

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:数组索引超出范围。 System.String.FormatHelper(System.Text.StringBuilder 结果,IFormatProvider 提供程序,System.String 格式,System.Object[] args)(在 /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/String .cs:1912) System.Text.StringBuilder.AppendFormat(IFormatProvider 提供程序,System.String 格式,System.Object[] args)(在 /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Text/StringBuilder.cs:第534章) System.Text.StringBuilder.AppendFormat(System.String 格式,System.Object arg0,System.Object arg1)(在 /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Text/StringBuilder.cs:第555章)

我犯了什么错误?

【问题讨论】:

  • 当然不相关,你拼错了Beginning
  • 如果你使用@,你必须为{和}使用转义字符,它们是{{和}}。单{表示会有字段编号。

标签: c# string stringbuilder


【解决方案1】:

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

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 来转义大括号:

左大括号和右大括号被解释为开始和结束一个 格式项。因此,您必须使用转义序列来显示 文字左大括号或右大括号。指定两个左大括号 ("{{") 在固定文本中显示一个左大括号 ("{"),或两个 右大括号 ("}}") 以显示一个右大括号 ("}")。大括号 格式项按它们的顺序依次解释 遭遇。不支持解释嵌套大括号。

【讨论】:

  • 我得到 System.FormatException,而不是 IndexOutOfRangeException。我想知道是否在其他地方抛出了异常。无论如何,我都会告诉她“{{”逃跑的事。
  • @EdPlunkett:鉴于堆栈跟踪,我怀疑这可能是 MS 实现和 Mono 之间的差异。
  • @JonSkeet 好点,谢谢——我没注意到它是单声道的。
  • 我认为转义字符不起作用,因为字符串是使用前面的 @ 创建的。这意味着照原样接受。一种解决方法是用 {2} 替换末尾的开头花括号,并将其添加为 AppendFormat 调用中的第三个参数“{”。
  • @EdPlunkett 感谢您的转义提示! :D 现在可以了 :)
猜你喜欢
  • 1970-01-01
  • 2020-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多