【问题标题】:How does C# string interpolation without an expression compile?没有表达式的 C# 字符串插值如何编译?
【发布时间】:2016-05-14 22:24:43
【问题描述】:

编译器如何处理没有表达式的插值字符串?

string output = $"Hello World";

它还会尝试格式化字符串吗?编译后的代码与带有表达式的代码有何不同?

【问题讨论】:

    标签: c# c#-6.0 string-interpolation


    【解决方案1】:

    对于这个 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 只在第二种情况下调用。

    【讨论】:

    • 谢谢。这就是我希望发生的事情。
    猜你喜欢
    • 2016-09-17
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2022-03-24
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多