如何使用带插值的逐字字符串?
How to use verbatim strings with interpolation?
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();
如何同时使用逐字字符串和内插字符串?
您可以将 $
和 @
前缀应用于同一字符串:
string s = $@"Result...
Adding ""{x}"" and {this.Y()} to foobar:
{x.GetLog()}";
因为introduced in C# 6, interpolated verbatim strings had to start with the tokens $@
, but starting with C# 8, you can use either $@
or @$
.
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();
如何同时使用逐字字符串和内插字符串?
您可以将 $
和 @
前缀应用于同一字符串:
string s = $@"Result...
Adding ""{x}"" and {this.Y()} to foobar:
{x.GetLog()}";
因为introduced in C# 6, interpolated verbatim strings had to start with the tokens $@
, but starting with C# 8, you can use either $@
or @$
.