2012-01-31 15 views
9

Powiel możliwe:
How to escape brackets in a format string in .Net
string.format format string containing {jak dodać {STRING Format C#

Próbowałam ciągu formatu jak ta, {Enum.Enum1 "Enum1String" } Próbowałem tego kodu

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)); 

      } 

ale to nie działa. Jak dodać {w formacie smyczkowym. Mam zamiar użyć stringbuilder.

+0

Wspaniale to działało. Dzięki –

Odpowiedz

26

Od tego MSDN FAQ:

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

Alternatywnie, za pomocą operatora @ gwarantuje, że łańcuch jest dokładnie przedstawiony jako że pojawia się w kodzie:

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

Operator @ nie zmieni tego, w jaki sposób string.format obsługuje "{" i "}". Przeniesienie ich poza string.format pozwala uniknąć problemu, tak, ale tak naprawdę * nie rozwiązuje * go. – Servy