我可以在逐字字符串中转义双引号吗?
在 C# 中的逐字字符串文字 (@"foo") 中,反斜杠不被视为转义符,因此使用 \" 来获取双引号不起作用。有没有办法在逐字字符串文字中获取双引号?
这显然行不通:
string foo = @"this \"word\" is escaped";
In a verbatim string literal (@"foo") in C#, backslashes aren't treated as escapes, so doing \" to get a double quote doesn't work. Is there any way to get a double quote in a verbatim string literal?
This understandably doesn't work:
string foo = @"this \"word\" is escaped";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用重复的双引号。
输出:
Use a duplicated double quote.
outputs:
使用双引号。
Use double quotation marks.
这应该有助于解决您可能遇到的任何问题:C# 文字
这是来自链接内容:
This should help clear up any questions you may have: C# literals
Here is a table from the linked content:
为了添加更多信息,您的示例将在没有
@
符号的情况下工作(它可以防止使用 \ 转义),这样:它可以双向工作,但我更喜欢双引号样式,因为它更容易例如,使用文件名(字符串中有很多 \)。
For adding some more information, your example will work without the
@
symbol (it prevents escaping with \), this way:It will work both ways but I prefer the double-quote style for it to be easier working, for example, with filenames (with lots of \ in the string).
更新:使用 C# 11 预览功能 - 原始字符串文字
历史:
GitHub 上有一项针对 C# 语言的提案,旨在更好地支持原始字符串文字。一个有效的答案是鼓励 C# 团队向该语言添加一项新功能(例如三重引号 - 像 Python)。
请参阅 https://github.com/dotnet/csharplang/discussions/89#discussioncomment- 257343
Update: With C# 11 Preview feature - Raw String Literals
History:
There is a proposal open in GitHub for the C# language about having better support for raw string literals. One valid answer, is to encourage the C# team to add a new feature to the language (such as triple quote - like Python).
see https://github.com/dotnet/csharplang/discussions/89#discussioncomment-257343
正如文档所述:
As the documentation says:
从 C#11 开始,您可以使用 原始字符串< /a>,由三个双引号分隔。
它们可以是单行或多行:
多行版本保留新行和缩进,但有趣的是,它会丢弃结束“”的缩进之前的字符,如上所述。并且,正如预期的那样,第一行是下面的行开头,最后一个是结束引号之前的,
您还可以使用
@"""
进行插值,例如注意:我在这个答案中将代码格式化为 python,因为C# 格式化程序还没有意识到这一点,而 python 格式化程序使这一点更具可读性
Since C#11 you can use raw strings, which are delimited by three double quotes.
They can be either single or multiline:
The multiline version keeps the new lines and indenting, but interestingly it discards the characters before the indentation of the closing """ as explained above. And, as expected, the first line is the one below the opening, and the last is the one before the closing quotes.
And you can also use
@"""
for interpolation, likeNOTE: I formatted the code as python in this answer, because the C# formatter is not aware of this yet, and python formatter keeps this more readable