【问题标题】:How to use verbatim strings with interpolation?如何使用带插值的逐字字符串?
【发布时间】:2015-10-16 18:46:01
【问题描述】:

在 C# 6 中有一个新特性:内插字符串。这些让您可以将表达式直接放入代码中。

而不是依赖索引:

string s = string.Format("Adding \"{0}\" and {1} to foobar.", x, this.Y());

上面变成:

string s = $"Adding \"{x}\" and {this.Y()} to foobar.";

但是,我们有很多跨行的字符串,使用逐字字符串(主要是 SQL 语句),如下所示:

string s = string.Format(@"Result...
Adding ""{0}"" and {1} to foobar:
{2}", x, this.Y(), x.GetLog());

将这些恢复为常规字符串似乎很麻烦:

string s = "Result...\r\n" +
$"Adding \"{x}\" and {this.Y()} to foobar:\r\n" +
x.GetLog().ToString();

如何同时使用逐字字符串和插值字符串?

【问题讨论】:

    标签: c# string-interpolation c#-6.0 verbatim-string


    【解决方案1】:

    您可以将$@ 前缀应用于同一个字符串:

    string s = $@"Result...
    Adding ""{x}"" and {this.Y()} to foobar:
    {x.GetLog()}";
    

    由于是introduced in C# 6逐字插值字符串必须以标记$@but starting with C# 8, you can use either $@ or @$开头。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-30
      • 2013-08-13
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多