字符串插值有什么意义?

What is the point of string interpolation?

乍一看,它似乎只是为每个嵌入表达式保存 2 个字符:

Console.WriteLine($"This is time number {i} that I, {name}, printed this statement.");
Console.WriteLine("This is time number "+i+" that I, "+name+", printed this statement.");

这真的值得整个语言功能吗?

话虽这么说,但我不得不承认,我确实更喜欢看花括号,所以我一直在使用字符串插值。但是为什么我更喜欢它呢?什么心理现象更喜欢 {hello} 而不是 "+hello+"?好像有点随意。

字符串插值还有其他好处可以保证整个语言的特性吗?还是真的只是为了可读性?

什么时候字符串插值不等同于 "+ => {+" => } 的简单文本替换?

我知道它被编译为 string.Format。所以生成的二进制文件是不同的,但执行似乎是一样的,有一些非常小的性能差异。

When is string interpolation not equivalent to a simple text replacement of "+ => { and +" => }?

你能用字符串插值做的任何事情最终都可以用连接来完成。但是插值可以更快地编写,更容易阅读并且可以(在某些情况下)在 运行 时间执行得更快。

一个例子:

var a = 1.23456;
var b = 2.3434;
var check = false;

Console.WriteLine($"Hello {a/2:g7}, it looks like {b%1:g4} {(check ? "really" : "no")}"); // Fast to write, shorter, easier to read
Console.WriteLine("Hello {0:g7}, it looks like {1:g4} {2}", a /2, b % 1, check ? "really" : "no"); // Lack of compile time safety (may be wrong number of parameters)
Console.WriteLine("Hello " + (a/2).ToString("g7") + ", it looks like " + (b%1).ToString("g4") + " " + (check ? "really" : "no")); // Harder to read and write

第三个代码示例 特别是 很难获得正确的间距(例如 no 之前的 space)。在这方面,使用字符串插值或 string.Format(第一行或第二行)要容易得多。

请注意,上面的代码实际上为第二个示例(带有 0:g7 的那个)绘制了比通常情况下更好的图片,因为 Console.WriteLinestring.Format内置逻辑(即通常第二行代码会更长)。

字符串插值及其对 FormattableString 的支持也开辟了一些生成 SQL 的技术,即 not open to SQL Injection - 但这可能超出了您的问题范围。

我认为答案在 String Interpolation 上的官方参考文档中:

String interpolation provides a more readable and convenient syntax to create formatted strings than a string composite formatting feature.

所以它本身并不是一个全新的语言功能来取代字符串连接...它更像是现有字符串格式函数的语法糖。换句话说,当您实际格式化字符串中的元素时,优势就会出现:

var birthdate = new DateTime(1990,9,22);

Console.WriteLine($"Your birthday is {birthdate:MMMM dd}!");      // string interpolation

Console.WriteLine("Your birthday is {0:MMMM dd}!", birthdate);    // implicit String.Format

var message = "Your birthday is " +
                String.Format("{0:MMMM dd}", birthdate) + "!";    // explicit String.Format

Console.WriteLine(message);

// Your birthday is September 22!

我刚刚想到另一个答案,为什么 {thing}"+thing+" 更具可读性。

当然有一个根本原因就是我们程序员很习惯把花括号看成一个整体。但是有一种特殊情况,引号看起来比花括号难看多了。

比较以下:

string s1 = "<div class=\"" + styling + "\">" + content + "</div>";
string s2 = "Field \"" + fieldname + "\" has been submitted with value \"" + fieldvalue + "\".";
string s3 = "select * from [" + dbname + "][" + schemaname + "][" + tablename + "] where " + fieldname + " = '" + escapedvalue + "'";
string s4 = "{\"jsonprop1\":{},\"jsonprop2\": \"" + value + "\"}";

以下内容:

string s1 = $"<div class=\"{styling}\">{content}</div>";
string s2 = $"Field \"{fieldname}\" has been submitted with value \"{fieldvalue}\".";
string s3 = $"select * from [{dbname}][{schemaname}][{tablename}] where " + fieldname + " = '{escapedvalue}'";
string s4 = $"{\"jsonprop1\":{},\"jsonprop2\": \"{value}\"}";

通常需要插入变量的字符串已经包含引号或单引号。这使得更多的引语难以用眼睛解析。 因此,简单地使用另一个选项作为转义字符是很好的。