你如何使用插值的逐字字符串?

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)

  • 相反(`@ $"..."`)不起作用,这使我来到这里. (54认同)
  • `$ @`在`@ $`不起作用的事实,当你想到它时就很有意义.当我开始使用这种语法时经常发生这种情况时,我总是对自己说:"插入这个逐字字符串"导致相反的情况没有意义. (35认同)
  • @Sinatr是的,它必须是`$ @"..."`按顺序. (12认同)