2012-01-31 11 views
9

Eventuali duplicati:
How to escape brackets in a format string in .Net
string.format format string containing {come aggiungere {in formato stringa C#

stavo cercando di stringa di formato come questo, {Enum.Enum1, "Enum1String" } Ho provato questo codice

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

      } 

ma non funziona. Come aggiungere {in formato stringa. Sto pensando di usare il costruttore di stringhe.

+0

Eccellente ha funzionato. Grazie –

risposta

26

Da questo MSDN FAQ:

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

alternativa, utilizzando l'operatore @ assicura che la stringa è rappresentata esattamente come appare nel codice:

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

L'operatore @ non cambierà il modo in cui string.format gestisce "{" e "}". Spostarli fuori da string.format evita il problema, sì, ma in realtà non lo * risolve *. – Servy

Problemi correlati