如何使用带有插值的原样字符串?

186

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

与依赖索引不同:

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

以上变为:

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

但是,我们有很多跨越多行的字符串使用verbatim字符串(主要是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();

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

1个回答

273
你可以同时对同一个字符串应用$@前缀。
string s = $@"Result...
Adding ""{x}"" and {this.Y()} to foobar:
{x.GetLog()}";

当在C# 6中引入时,插值逐字字符串必须以"$@"标记开头,但从C# 8开始,你可以使用"$@"或"@$"。
自C#11起,我们还有原始字符串字面量,它为像这样的大块提供了更好的方式。
你可以使用"""而不是@,并且仍然可以与$结合使用。
string s = $"""
    Result...
    Adding "{x}" and {this.Y()} to foobar:
    {x.GetLog()}
    """;

这将产生与第一个示例相同的输出,但更易读。C#编译器将从每一行的关闭"""之前删除任何空格,因此字符串可以具有与您的代码相同的缩进。

C# 8 的解释链接已更改。微软删除了解释,并用直接链接到详细页面进行了替换。 - Trisped

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接