[英]How does C# string interpolation without an expression compile?
How does the compiler handle interpolated strings without an expressions? 编译器如何处理没有表达式的插值字符串?
string output = $"Hello World";
Will it still try to format the string? 它还会尝试格式化字符串吗? How does the compiled code differ from that of one with an expression?
编译代码与具有表达式的代码有何不同?
For this C# code: 对于这个C#代码:
string output = $"Hello World";
int integer = 5;
string output2 = $"Hello World {integer}";
Console.WriteLine(output);
Console.WriteLine(output2);
I get this when I compile and then decompile (via ILSpy): 我编译然后反编译(通过ILSpy)时得到这个:
string value = "Hello World";
int num = 5;
string value2 = string.Format("Hello World {0}", num);
Console.WriteLine(value);
Console.WriteLine(value2);
So it seems that the compiler is smart enough not to use string.Format
for the first case. 因此,似乎编译器足够聪明,不能在第一种情况下使用
string.Format
。
For completeness, here is the IL code: 为了完整性,这里是IL代码:
IL_0000: nop
IL_0001: ldstr "Hello World"
IL_0006: stloc.0
IL_0007: ldc.i4.5
IL_0008: stloc.1
IL_0009: ldstr "Hello World {0}"
IL_000e: ldloc.1
IL_000f: box [mscorlib]System.Int32
IL_0014: call string [mscorlib]System.String::Format(string, object)
IL_0019: stloc.2
IL_001a: ldloc.0
IL_001b: call void [mscorlib]System.Console::WriteLine(string)
IL_0020: nop
IL_0021: ldloc.2
IL_0022: call void [mscorlib]System.Console::WriteLine(string)
IL_0027: nop
IL_0028: ret
It is clear here too that string.Format
is only called for the second case. 很明显,
string.Format
仅在第二种情况下被调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.