我可以转义逐字字符串中的双引号吗?

问题描述 投票:0回答:7

在 C# 中的逐字字符串文字 (@"foo") 中,反斜杠不被视为转义符,因此使用 \" 来获取双引号不起作用。有没有办法在逐字字符串中获取双引号字面意思?

这显然行不通:

string foo = @"this \"word\" is escaped";
c# string escaping literals verbatim-string
7个回答
925
投票

使用重复的双引号。

@"this ""word"" is escaped";

输出:

this "word" is escaped

119
投票

使用双引号。

string foo = @"this ""word"" is escaped";

96
投票

为了添加更多信息,您的示例将在没有

@
符号的情况下工作(它可以防止使用 \ 转义),这样:

string foo = "this \"word\" is escaped!";

它可以两种方式工作,但我更喜欢双引号样式,因为它更容易工作,例如,使用文件名(字符串中有很多 \)。


95
投票

这应该有助于解决您可能遇到的任何问题:C# 文字

这是链接内容的表格:

常规文字 逐字逐字 结果字符串
"Hello"
@"Hello"
Hello
"Backslash: \\"
@"Backslash: \"
Backslash: \
"Quote: \""
@"Quote: """
Quote: "
"CRLF:\r\nPost CRLF"
@"CRLF:
Post CRLF"
CRLF:
Post CRLF

8
投票

更新:使用 C# 11 预览功能 - 原始字符串文字

string foo1 = """
   this "word" is escaped
   """;

string foo2 = """this "word" is escaped""";

历史:

GitHub 上有一项针对 C# 语言的提案,旨在更好地支持原始字符串文字。一个有效的答案是鼓励 C# 团队向该语言添加一项新功能(例如三重引号 - 像 Python)。

参见https://github.com/dotnet/csharplang/discussions/89#discussioncomment-257343


2
投票

正如文档所说:

简单的转义序列...按字面解释。只有引号转义序列 (

""
) 不会按字面解释;它产生一个双引号。此外,如果是逐字插入的字符串大括号转义序列(
{{
}}
)不会按字面解释;他们产生单大括号字符。


0
投票

自 C#11 起,您可以使用 原始字符串,它们由三个双引号分隔。

它们可以是单行或多行:

var singleLine = """Anything, including " is supported here without escaping""";
var multiLine = """
    Any blank after the opening quotes in previous line is discarded.
    This is WYSIWYG, including "quotes" and new lines.
        This line is indented by 4 characters, not 8, because
    the number of characters before the closing quotes
    of the next line are removed from each line.
    """;

多行版本保留新行和缩进,但有趣的是,它丢弃了结束“”的缩进之前的字符,如上所述。

您还可以使用

@"""
进行插值,例如

var @"""
    The value of "{property}" is:
    {value}
    """;
© www.soinside.com 2019 - 2024. All rights reserved.