字符串插值的意义是什么?

Nac*_*ica 3 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.");
Run Code Online (Sandbox Code Playgroud)

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

话虽这么说,我不得不承认,我确实更喜欢看花括号,因此我一直在使用字符串插值。但是,为什么我更喜欢它呢?什么心理现象更喜欢{hello}"+hello+"?似乎有点武断。

字符串插值还有其他好处,可以保证整个语言功能吗?还是真的只是关于可读性?

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

我知道它已被编译为string.Format。因此,生成的二进制文件是不同的,但是执行似乎是相同的,给与或取一些非常小的性能差异。

Gra*_*ICA 6

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

字符串复合格式设置功能相比,字符串插值提供了更易读和方便的语法来创建格式化字符串。

因此,代替字符串连接本身并不是一种全新的语言功能……它更像是现有字符串格式函数上的语法糖。换句话说,当您实际格式化字符串中的元素时,这些优点就会显现出来:

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!
Run Code Online (Sandbox Code Playgroud)


mjw*_*lls 5

什么时候字符串插值不等同于简单地替换“ + => {和+” =>}?

字符串插值可以做的任何事情最终都可以通过串联来完成。但是插值可以更快地编写,更容易阅读,并且在某些情况下可以在运行时更快地执行。

一个例子:

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
Run Code Online (Sandbox Code Playgroud)

就正确设置间距(例如之前的空格)而言,第三个代码示例特别困难nostring.Format在这方面,使用字符串插值或(第一或第二行)要容易得多。

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

字符串插值及其支持FormattableString还为生成SQL带来了一些技术,这些技术对SQL注入不开放 -但这可能不在您的问题范围之内。