双引号可以像这样转义:

string test = @"He said to me, ""Hello World"". How are you?";

但这涉及到向字符串中添加字符“。是否有c#函数或其他方法来转义双引号,以便不需要更改字符串?


当前回答

请解释你的问题。你说:

但这涉及到向字符串中添加字符“。

这是什么问题?你不能输入string foo = " foo "bar"";,因为这会引发编译错误。至于添加部分,在字符串大小方面,这是不正确的:

@"""".Length == 1

"\"".Length == 1

其他回答

在c#中,至少有四种方法可以在字符串中嵌入引号:

带反斜杠的转义引号 字符串前面加@并使用双引号 使用对应的ASCII字符 使用十六进制Unicode字符

详细说明请参考本文件。

在c#中,你可以使用反斜杠在字符串中加入特殊字符。 例如,要输入“,你需要写\”。 你可以用反斜杠写很多字符:

与其他字符反斜杠

  \0 nul character
  \a Bell (alert)
  \b Backspace
  \f Formfeed
  \n New line
  \r Carriage return
  \t Horizontal tab
  \v Vertical tab
  \' Single quotation mark
  \" Double quotation mark
  \\ Backslash

任何数字字符替换:

  \xh to \xhhhh, or \uhhhh - Unicode character in hexadecimal notation (\x has variable digits, \u has 4 digits)
  \Uhhhhhhhh - Unicode surrogate pair (8 hex digits, 2 characters)

请解释你的问题。你说:

但这涉及到向字符串中添加字符“。

这是什么问题?你不能输入string foo = " foo "bar"";,因为这会引发编译错误。至于添加部分,在字符串大小方面,这是不正确的:

@"""".Length == 1

"\"".Length == 1

c# 6中值得一提的另一件事是插值字符串可以与@一起使用。

例子:

string helloWorld = @"""Hello World""";
string test = $"He said to me, {helloWorld}. How are you?";

Or

string helloWorld = "Hello World";
string test = $@"He said to me, ""{helloWorld}"". How are you?";

在这里检查运行代码!

在这里查看插值的参考!

你可以用两种方式使用反斜杠:

string str = "He said to me, \"Hello World\". How are you?";

它打印:

He said to me, "Hello World". How are you?

这和打印出来的完全一样

string str = @"He said to me, ""Hello World"". How are you?";

这里是一个演示。

仍然是你的弦的一部分。

你可以查看Jon Skeet的Strings in c# and . net文章了解更多信息。