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
(不太便携),或将其提取到本地变量中,但有些情况下,如果不超过一行,则无法减少语义强度。
是否简单的认为对于长字符串,不应使用字符串插值?
对于更长的字符串,我们应该只使用StringBuilder
吗?
var multi4 = new StringBuilder()
.AppendFormat("Width: {0}", width).AppendLine()
.AppendFormat("Height: {0}", height).AppendLine()
.AppendFormat("Background: {0}", background).AppendLine()
.ToString();
还有更优雅的方式吗?