2012-01-31 33 views
9

可能重複:
How to escape brackets in a format string in .Net
string.format format string containing {如何添加{String中格式化C#

我試圖格式字符串這樣, {Enum.Enum1, 「Enum1String」 } 我試過這個代碼

foreach (KeyValuePair<int, string> p in Helper.Dict) 
      { 
       // file.WriteLine(string.Format("{0} | {1}",p.Key,p.Value)); 
       file.WriteLine(string.Format("{Enum.{0},\"{1}\"}", p.Value,p.Value)); 

      } 

但它不起作用。如何添加{以字符串格式。 我在想使用stringbuilder。

+0

非常好用。謝謝 – 2012-01-31 17:54:59

回答

26

從這個MSDN FAQ

string s = String.Format("{{ hello to all }}"); 
Console.WriteLine(s); //prints '{ hello to all }' 
0

另外,使用@操作確保字符串精確表示,它出現在代碼:

foreach (KeyValuePair<int, string> p in Helper.Dict) 
{ 
     // file.WriteLine(string.Format("{0} | {1}",p.Key,p.Value)); 
     file.WriteLine(@"{" + string.Format("Enum.{0},\"{1}\"", p.Value,p.Value) + @"}"); 
} 
+1

@操作符不會改變string.format如何處理「{」和「}」。將它們移動到string.format之外可以避免這個問題,是的,但它實際上並不解決它。 – Servy 2012-01-31 17:56:16