2016-09-19 29 views
0

我有一個模板字符串中的定義:StringBuilder的AppendFormat拋出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:數組索引超出範圍。 (在/ Users/builduser/buildslave/mono/build/mcs/class/corlib/System/System /目錄中的System.String.FormatHelper(System.Text.StringBuilder結果,IFormatProvider提供程序,System.String格式,System.Object []參數) 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 (在/ Users/builduser/buildslave/mono/build/mcs/class /目錄下).sxt/StringBuilder.cs:534) System.Text.StringBuilder.AppendFormat(System.String format,System.Object arg0,System.Object arg1) corlib/System.Text/StringBuilder.cs:555)

我犯了什麼錯誤?

+3

無關當然,你拼錯'開始'。 –

+2

如果您使用@,則必須對{和}}使用{和}轉義字符。單一{意味着會有場數字。 –

回答

3

我會假設類模板的開放大括號被解釋爲佔位符。您需要轉義任何您需要作爲文字字符處理的大括號。

打開和關閉括號被解釋爲開始和結束 格式項:

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 

埃德賓吉指出,通過使用雙括號符號,{{as covered in the MSDN逃避括號。因此,您必須使用轉義序列來顯示 文字左右大括號或右大括號。在固定文本中指定兩個開放大括號 (「{{」)以顯示一個大括號(「{」)或兩個 大括號(「}}」)以顯示一個大括號(「}」)。 格式項目中的大括號將按照它們遇到的 的順序進行順序解釋。不支持解釋嵌套大括號。

+1

我得到System.FormatException,而不是IndexOutOfRangeException。我想知道這個異常是否被拋出別的地方。無論如何,我會告訴她關於「{{」逃避。 –

+2

@EdPlunkett:鑑於堆棧跟蹤,我懷疑這可能是MS實現和Mono之間的區別。 –

+0

@JonSkeet好點,謝謝 - 我沒有注意到它是單聲道的。 –

相關問題