[英]How does C# string interpolation without an expression compile?
編譯器如何處理沒有表達式的插值字符串?
string output = $"Hello World";
它還會嘗試格式化字符串嗎? 編譯代碼與具有表達式的代碼有何不同?
對於這個C#代碼:
string output = $"Hello World";
int integer = 5;
string output2 = $"Hello World {integer}";
Console.WriteLine(output);
Console.WriteLine(output2);
我編譯然后反編譯(通過ILSpy)時得到這個:
string value = "Hello World";
int num = 5;
string value2 = string.Format("Hello World {0}", num);
Console.WriteLine(value);
Console.WriteLine(value2);
因此,似乎編譯器足夠聰明,不能在第一種情況下使用string.Format
。
為了完整性,這里是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
很明顯, string.Format
僅在第二種情況下被調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.