Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

.net - How can I use escape characters with string interpolation in C# 6?

I've been using string interpolation and love it. However, I have an issue where I am trying to include a backslash in my output, but I am not able to get it to work.

I want something like this...

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

I want the output of combo to be:

myDomainmyUserName

I get a syntax error about the being an escape character. If I put in \ then the syntax error is gone, but the output is myDomain\myUsername.

How can I include escaped characters in an interpolated string?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...