问题描述
在C#6中,有一个新功能:内插字符串.这些使您可以将表达式直接放入代码中.
In C# 6 there is a new feature: interpolated strings. These let you put expressions directly into code.
而不是依赖索引:
string s = string.Format("Adding \"{0}\" and {1} to foobar.", x, this.Y());
以上内容变为:
string s = $"Adding \"{x}\" and {this.Y()} to foobar.";
但是,我们使用这样的逐字字符串(主要是SQL语句)在多行中有很多字符串:
However, we have a lot of strings across multiple lines using verbatim strings (mainly SQL statements) like this:
string s = string.Format(@"Result...
Adding ""{0}"" and {1} to foobar:
{2}", x, this.Y(), x.GetLog());
将它们恢复为常规字符串似乎很麻烦:
Reverting these to regular strings seems messy:
string s = "Result...\r\n" +
$"Adding \"{x}\" and {this.Y()} to foobar:\r\n" +
x.GetLog().ToString();
如何同时使用逐字和内插字符串?
How to use both verbatim and interpolated strings together?
推荐答案
您可以将 $
和 @
前缀都应用于同一字符串:
You can apply both $
and @
prefixes to the same string:
string s = $@"Result...
Adding ""{x}"" and {this.Y()} to foobar:
{x.GetLog()}";
由于被引入C#6 ,插入的逐字字符串必须以标记 $ @
,但从C#8开始,您可以使用 $ @
或 @ $
.
Since being introduced in C# 6, interpolated verbatim strings had to start with the tokens $@
, but starting with C# 8, you can use either $@
or @$
.
这篇关于如何在插值中使用逐字字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!