乍一看,它似乎只是为每个嵌入表达式保存 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
。因此生成的二进制文件不同,但执行似乎是相同的,只是存在一些极小的性能差异。
最佳答案
我认为答案在 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!
关于c# - 字符串插值有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57965985/