Kei*_*ith 121 c# string-interpolation verbatim-string c#-6.0
在C#6中有一个新功能:插值字符串.
这些允许您将表达式直接放入代码中,而不是依赖于索引:
string s = string.Format("Adding \"{0}\" and {1} to foobar.", x, this.Y());
Run Code Online (Sandbox Code Playgroud)
变为:
string s = $"Adding \"{x}\" and {this.Y()} to foobar.";
Run Code Online (Sandbox Code Playgroud)
但是,我们在使用逐字符串(主要是SQL语句)的多行中有很多字符串,如下所示:
string s = string.Format(@"Result...
Adding ""{0}"" and {1} to foobar:
{2}", x, this.Y(), x.GetLog());
Run Code Online (Sandbox Code Playgroud)
将这些恢复为常规字符串似乎很麻烦:
string s = "Result...\r\n" +
$"Adding \"{x}\" and {this.Y()} to foobar:\r\n" +
x.GetLog().ToString();
Run Code Online (Sandbox Code Playgroud)
如何同时使用逐字和插值字符串?
Kei*_*ith 173
您可以将两者$
和@
前缀应用于同一个字符串:
string s = $@"Result...
Adding ""{x}"" and {this.Y()} to foobar:
{x.GetLog()}";
Run Code Online (Sandbox Code Playgroud)