c# - 字符串插值有什么意义?

标签 c# 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。因此生成的二进制文件不同,但执行似乎是相同的,只是存在一些极小的性能差异。

最佳答案

我认为答案在 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/

相关文章:

c# - 返回基于 C# 中的另一个列表过滤的列表

c# - SteamAPI_Init() 失败。有关详细信息,请参阅 Valve 的文档或此行上方的注释。 | Steamworks.NET

c# - 将命令按钮动态添加到 GridView

perl - 为什么这种预期的插值被解释为 Perl 的除法?

javascript - 在 Angular2 应用程序中使用字符串插值从数组中提取值

Kotlin中双数的字符串插值

c# - 你调用的对象是空的。使用 TPM 设备客户端发送消息时

c# - 使用正则表达式从字符串中提取数据

string - 如何在 Elixir 中评估或执行字符串插值?

linux - 如何在复杂的文本文件中替换 shell 变量