C#6提供了对内插字符串文字的编译器支持,语法如下:
var person = new { Name = "Bob" };
string s = $"Hello, {person.Name}.";
这对于短字符串很好,但是如果你想产生一个更长的字符串,必须在一行中指定吗?
使用其他类型的字符串,您可以:
var multi1 = string.Format(@"Height: {0}
Width: {1}
Background: {2}",
height,
width,
background);
或者:
var multi2 = string.Format(
"Height: {1}{0}" +
"Width: {2}{0}" +
"Background: {3}",
Environment.NewLine,
height,
width,
background);
我找不到一种方法来实现这一点,如果没有一行字符串插值:
var multi3 = $"Height: {height}{Environment.NewLine}Width: {width}{Environment.NewLine}Background: {background}";
我意识到,在这种情况下,你可以用\r\n
代替Environment.NewLine
(便携性较差),或者把它拉到本地,但在某些情况下,你无法在不失go 语义强度的情况下将其减少到一行以下.
是不是很简单,字符串插值不应该用于长字符串?
我们应该用StringBuilder
来表示更长的字符串吗?
var multi4 = new StringBuilder()
.AppendFormat("Width: {0}", width).AppendLine()
.AppendFormat("Height: {0}", height).AppendLine()
.AppendFormat("Background: {0}", background).AppendLine()
.ToString();
还是有更优雅的?