开发者

How to easily display double quotes in strings in C#?

If you have a string with a numerous double quotes,

in PHP you can do this:

file.WriteLine('<controls:FormField Name="Strasse" LabelText="Strasse">');

in C# you have to do this:

file.WriteLine("<controls:FormField Name=\"Strasse\" LabelText=\"Strasse\">");

Is there a way in C# to do what you can do above in PHP, something like the @"c:\temp" which you can do so that 开发者_开发知识库you don't need double slashes?

Thanks Fredrik, that makes even quotes and curly brackets in a String.Format fairly readable:

    file.WriteLine(String.Format(@"<TextBox Text=""{{Binding {0}}}""
 Style=""{{DynamicResource FormularFieldTextBox}}""/>", fieldName));


There are two ways to represent quotes in C# strings:

file.WriteLine("<controls:FormField Name=\"Strasse\" LabelText=\"Strasse\">");
file.WriteLine(@"<controls:FormField Name=""Strasse"" LabelText=""Strasse"">");


"<controls:FormField Name='Strasse' LabelText='Strasse'>".Replace("'", "\"")

Which isn't great, but about the only option.

Or @"""" insted of \" you can use ""


I would recommend avoiding some bizarre way like this:

const char doubleQuote = '"';

Console.WriteLine("<controls:FormField Name={0}Strasse{0} LabelText={0}Strasse{0}>", doubleQuote);


I would recommend using a resource file to store the string constants. This increases elegance and code readability. Also, quotes and special characters can be displayed without messing around with too many escape sequences.

You can create a resource file entry like,

String Name(Key) => FormFieldControl
Value => <controls:FormField Name="{0}" LabelText="{1}">

This can be used in code like

const string fieldName = "Strasse";
Console.WriteLine(ResourceFile.FormFieldControl, fieldName, fieldName);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜