假设我遵守了代码:
Console.WriteLine("Value1: " + SomeEnum.Value1.ToString() + "\r\nValue2: " +
SomeOtherEnum.Value2.ToString());
编译器会将此优化为:
Console.WriteLine("Value1: " + SomeEnum.Value1 + "\r\nValue2: " +
SomeOtherEnum.Value2);
我已经用IL反汇编程序检查了它并且有调用
IL_005a: callvirt instance string [mscorlib]System.Object::ToString()
我不知道JIT是否会对此进行优化。
答案 0 :(得分:3)
不,这是相反的方式。这样:
Console.WriteLine("Value1: " + SomeEnum.Value1 + "\r\nValue2: " +
SomeOtherEnum.Value2);
由编译器翻译成(相当于)这个:
string s = String.Concat("Value1: ", SomeEnum.Value1.ToString(), "\r\n Value2: ", SomeOtherEnum.Value2.ToString());
Console.WriteLine(s);
在这两种情况下,都会生成相同的IL。如果您在询问JIT是否将其转换为:
string s = String.Concat("Value1: ", "Value1", "\r\n Value2: ", "Value2");
Console.WriteLine(s);
然后答案是否定的。虽然我想知道为什么那对你来说会有问题?