双引号可以像这样转义:

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

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


当前回答

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 foo = " foo "bar"";,因为这会引发编译错误。至于添加部分,在字符串大小方面,这是不正确的:

@"""".Length == 1

"\"".Length == 1

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

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文章了解更多信息。

2022年更新:以前的答案是“不”。然而,c# 11引入了一个叫做“原始字符串字面量”的新特性。引用微软文档:

从c# 11开始,您可以使用原始字符串字面值更容易地创建多行字符串,或使用任何需要转义序列的字符。原始字符串字面量不需要使用转义序列。您可以编写字符串,包括空格格式,以您希望它在输出中出现的方式。”

来源:https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/ raw-string-literals

示例:所以使用原来的例子,你可以这样做(注意原始字符串文字总是以三个或更多引号开头):

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

在c# 11.0预览版中,您可以使用原始字符串字面值。

Raw string literals are a new format for string literals. Raw string literals can contain arbitrary text, including whitespace, new lines, embedded quotes, and other special characters without requiring escape sequences. A raw string literal starts with at least three double-quote (""") characters. It ends with the same number of double-quote characters. Typically, a raw string literal uses three double quotes on a single line to start the string, and three double quotes on a separate line to end the string.

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

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?";

在这里检查运行代码!

在这里查看插值的参考!