如何在 C# 中轻松显示字符串中的双引号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1594600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to easily display double quotes in strings in C#?
提问by Edward Tanguay
If you have a string with a numerous double quotes,
如果您有一个带有多个双引号的字符串,
in PHP you can do this:
在 PHP 中你可以这样做:
file.WriteLine('<controls:FormField Name="Strasse" LabelText="Strasse">');
in C# you have to do this:
在 C# 中,你必须这样做:
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?
有没有办法在 C# 中做你可以在 PHP 中做的事情,比如 @"c:\temp" ,你可以这样做,这样你就不需要双斜线了?
Thanks Fredrik, that makes even quotes and curly brackets in a String.Format fairly readable:
感谢 Fredrik,这使得 String.Format 中的引号和大括号也相当可读:
file.WriteLine(String.Format(@"<TextBox Text=""{{Binding {0}}}""
Style=""{{DynamicResource FormularFieldTextBox}}""/>", fieldName));
采纳答案by Fredrik M?rk
There are two ways to represent quotes in C# strings:
在 C# 字符串中有两种表示引号的方法:
file.WriteLine("<controls:FormField Name=\"Strasse\" LabelText=\"Strasse\">");
file.WriteLine(@"<controls:FormField Name=""Strasse"" LabelText=""Strasse"">");
回答by Yuriy Faktorovich
"<controls:FormField Name='Strasse' LabelText='Strasse'>".Replace("'", "\"")
Which isn't great, but about the only option.
这不是很好,但关于唯一的选择。
Or @"""" insted of \" you can use ""
或者@"""" insted of \" 你可以使用""
回答by Greg
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);
回答by Palladin
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);