滥用C#6.0的新插值字符串

时间:2018-03-18 15:54:49

标签: c# string-interpolation

我认为来自C#6.0的插值字符串是迄今为止最实用的字符串。但是,如果您的字符串如下所示,使用插值有什么意义:

string str0 = $"{chatType + prefix + group + name} > {message}";

你会如何格式化?正如你所看到的,我使用C#的字符串插值以及concat符号'+',这看起来有点奇怪。

此外,当有人滥用此功能时,有人可以解释我,例如:

static string str1 = $"{str2}:"

而不是:

static string str2 = str1 + ":"

1 个答案:

答案 0 :(得分:2)

格式为:

string str0 = $"{chatType}{prefix}{group}{name} > {message}";

据我所知,插值字符串或string.Format的好处应该是在内存使用中。将字符串添加到字符串时,会在内存中创建一个新字符串。所以:

string x = a + b + c + d;

为a + b创建一个字符串,为该加+ c创建一个字符串,为该+ d创建另一个字符串。因此在内存中创建了三个字符串,只需要一个字符串。

对我来说,显而易见的好处是它看起来更漂亮,更整洁,你不会在整个地方获得双引号,更容易看到结果字符串的样子。它只是一种使用string.format的更好方法。