Escaping Quotes inside new C# 6 String Syntax

断了今生、忘了曾经 提交于 2019-11-30 00:12:00

问题


I'm really excited about the new features in C# 6, including the new string syntax:

var fullName = $"My Name is {FirstName} {LastName}";

However, I can't figure out how to escape quotes inside the braces to do the follow:

bool includePrefix = true;

var fullName = $"My name is {includePrefix ? "Mr. " : ""}{FirstName} {LastName}";

C# 6 doesn't like that. I've had to revert to using String.Format in that second case. Is it possible to escape quotes using the new syntax?

Update: Yes, I have tried using the \ escape, but it's not recognized.


回答1:


wrap your logic inside parentheses, inside the brackets:

var fullName = $"My name is {(includePrefix ? "Mr. " : "")}{FirstName} {LastName}";



回答2:


Regularly to escape quotes you need to use a slash (i.e. \").

However, this is not the issue here, as you don't need to escape, you're just missing parentheses over the expression.

This works:

bool includePrefix = true;
var fullName = $"My name is {(includePrefix ? "Mr. " : "")}{FirstName} {LastName}";


来源:https://stackoverflow.com/questions/33001477/escaping-quotes-inside-new-c-sharp-6-string-syntax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!