2011-05-13 57 views
10

可能重複:
How to escape brackets in a format string in .Net把{在逐字字符串與C#

如何把{}在逐字字符串中的C#?

using System; 

class DoFile { 

    static void Main(string[] args) { 
     string templateString = @" 
     \{{0}\} 
     {1} 
     {2} 
     "; 
     Console.WriteLine(templateString, "a", "b", "c"); 
    } 
} 

,當我在逐字字符串中使用「{」或「}」我得到的錯誤,我想這是因爲「{」或「}」用於參數標記,如{0}, {1}, {2}\{不起作用。

Unhandled Exception: System.FormatException: Input string was not in a correct format. 
    at System.String.ParseFormatSpecifier (System.String str, System.Int32& ptr, System.Int32& n, System.Int32& width, System.Boolean& left_align, System.String& format) [0x00000] in <filename unknown>:0 
    at System.String.FormatHelper (System.Text.StringBuilder result, IFormatProvider provider, System.String format, System.Object[] args) [0x00000] in <filename unknown>:0 
+0

你可以包含失敗的代碼行嗎?看起來你正在使用一個可以處理{。 – n8wrl 2011-05-13 19:38:43

+1

這是一個問題,因爲使用'Format',而不是因爲使用逐字字符串。 – 2011-05-13 19:39:38

回答

14

我們必須用雙大括號逃跑..

{{}}分別..

類似下面

string.Format("This is a format string for {0} with {{literal brackets}} inside", "test"); 

這對於測試格式字符串{字面括號}裏面

8

你放兩個像這樣{{}}

0

{}放在一個字符串中沒有什麼特別之處,它們不應該被轉義。此外,轉義字符\在@分隔字符串中沒有效果。

要以String.Format方法的格式使用字面值{},請將它們加倍。所以,你的格式字符串應該是:

string templateString = @" 
    {{{0}}} 
    {1} 
    {2} 
    ";