在 C # 6中如何使用带字符串插值的转义字符?

我一直在用字符串插值,我很喜欢。但是,我遇到了一个问题,我试图在输出中包含一个反斜杠,但是我不能让它工作。

我想要这样的东西。

var domain = "mydomain";
var userName = "myUserName";
var combo = $"{domain}\{userName}"

我希望 组合拳的输出是:

myDomain\myUserName

我得到一个关于转义字符的语法错误。如果我输入,那么语法错误就消失了,但输出是 我的域名我的用户名

如何在内插字符串中包含转义字符?

71528 次浏览
$"{domain}\\{user}"

Works fine - escaping works as usual (except when escaping {). At least on .NET 4.6 and Visual Studio 14.0.22823 D14REL.

If it doesn't work for some reason (maybe you're using an older version of the compiler?), you could also try being more explicit:

$"{domain}{@"\"}{user}"

You can do this, using both the $@. The order is important.

var combo = $@"{domain}\{userName}";

The original question mentions specifically C# 6. As commented, C# 8 no longer cares for the order.

Escaping with a backslash(\) works for all characters except a curly brace.

If you are trying to escape a curly brace ({ or }), you must use \{\{ or }} per $ - string interpolation (C# reference)

... All occurrences of double curly braces (“\{\{“ and “}}”) are converted to a single curly brace.

If I did not misunderstand, the solution is real simple:

var domain = "mydomain";
var userName = "myUserName";
var combo = $"\{\{{domain}}}\\\{\{{userName}}}";
Console.WriteLine(combo);

I share birdamongmen's answer as well as the good reference provided there.

Eduardo is correct. You escape curly braces by doubling up. Therefore, if you wanted to output the domain variable as {mydomain} you would need to do:

$"\{\{{domain}}}";

Furthermore, assuming that the current date is 1 Sept 2016, doing this:

$"The date is {DateTime.Now}";

would output something like "The date is 2016/09/01 3:04:48 PM" depending on your localization. You can also format the date by doing:

$"The date is {DateTime.Now : MMMM dd, yyyy}";

which would output "The date is September 1, 2016". Interpolated strings are much more readable. Good answer Eduardo.

The rule for escape the backslash in an interpolated string is to duplicate the backslash:

var domain = "mydomain";
var userName = "myUserName";
var combo = $"{domain}\\{userName}";

Console output

But if you also use the interpolated string as a verbatim string then you don't need to escape the backslash:

var domain = "mydomain";
var userName = "myUserName";
var combo = $@"{domain}\{userName}";

And you get the same:

Console output

For a tutorial about interpolated strings (in Spanish): see a video about interpolated strings

You can use this -

' First, declare the curly brackets as chars
Dim LeftBrace As Char = "{"
Dim RightBrace As Char = "}"


' Then in your string, use it like this:
Dim myStr As String = $"This is a {LeftBrace}String{RightBrace}"


' Now, the output will be
' This is a {string}code here