相关疑难解决方法(0)

C#6中的长字符串插补行

我发现虽然字符串插值在应用于我现有的代码库的字符串格式调用时非常好,但考虑到通常首选的列限制,字符串对于单行很快就会变得太长.特别是当插值的表达式很复杂时.使用格式字符串,您可以将变量列表拆分为多行.

var str = string.Format("some text {0} more text {1}",
    obj1.property,
    obj2.property);
Run Code Online (Sandbox Code Playgroud)

有没有人有任何打破这些线路的首选方法?

我想你可以这样做:

var str = $"some text { obj1.property }" +
  " more text { obj2.property };
Run Code Online (Sandbox Code Playgroud)

c# c#-6.0

122
推荐指数
4
解决办法
3万
查看次数

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

在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)

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

c# string-interpolation verbatim-string c#-6.0

121
推荐指数
1
解决办法
2万
查看次数