它是允许您创建插值字符串的符号,它是 C# 6 的新功能,我喜欢它。
它也是一个语法糖,我会在最后解释它的含义。
让我们看看实际情况。看下面的代码
public string Receive(int value)
{
return String.Format("Received: {0}", value);
}
public string Receive6(int value)
{
return $"Received: {value}";
}
编译后会发生什么
它们将具有相同的 IL 实现,请看这里来自 Receive
的 IL(处于调试模式,未优化)
.method public hidebysig instance string Receive (int32 'value') cil managed
{
// Method begins at RVA 0x22d4
// Code size 22 (0x16)
.maxstack 2
.locals init (
[0] string
)
IL_0000: nop
IL_0001: ldstr "Received: {0}"
IL_0006: ldarg.1
IL_0007: box [mscorlib]System.Int32
IL_000c: call string [mscorlib]System.String::Format(string, object)
IL_0011: stloc.0
IL_0012: br.s IL_0014
IL_0014: ldloc.0
IL_0015: ret
} // end of method Program::Receive
现在让我们从 Receive6 中查看 IL(处于调试模式,未优化)
.method public hidebysig instance string Receive6 (int32 'value') cil managed
{
// Method begins at RVA 0x22f8
// Code size 22 (0x16)
.maxstack 2
.locals init (
[0] string
)
IL_0000: nop
IL_0001: ldstr "Received: {0}"
IL_0006: ldarg.1
IL_0007: box [mscorlib]System.Int32
IL_000c: call string [mscorlib]System.String::Format(string, object)
IL_0011: stloc.0
IL_0012: br.s IL_0014
IL_0014: ldloc.0
IL_0015: ret
} // end of method Program::Receive6
正如您亲眼所见,IL 几乎相同。
现在让我们了解一下什么是语法糖
在计算机科学中,语法糖是一种编程语言中的语法,旨在使事物更易于阅读或表达。它使人类使用的语言“更甜美”:可以更清晰、更简洁地表达事物,或者以某些人可能更喜欢的另一种风格表达。
来自https://en.wikipedia.org/wiki/Syntactic_sugar
因此,如果要编写大量 string.Format,请使用字符串插值,编译器将为您工作并转换您编写的语法,在另一个代码中,在这种情况下,使用 string.Format。
我可以使用像 string.Format 这样的格式化选项吗?
是的,你可以,看下面
public static string Receive(int value)
=> string.Format("Received: {0, 15:C}", value);
public static string Receive6(int value)
=> $"Received: {value,15:C}";
Console.WriteLine(Receive(1));
Console.WriteLine(Receive6(1));
Console.WriteLine($"Current data: {DateTime.Now: MM/dd/yyyy}")
输出(我的文化是 pt-br)
Received: R$ 1,00
Received: R$ 1,00
Current data: 01/01/2016
Obs.:我想提一下,没有性能差异,因为使用字符串插值 e string.Format 是完全一样的