@Jon Skeet:查看生成的 MSIL 后,这就是我发现的内容,这真的很有趣。这是我编写的两种测试方法:
static void ClassicalIf(bool condition)
{
int i = 0;
if (condition)
i = 1;
else
i = 2;
}
static void InlineIf(bool condition)
{
int i = condition ? 1 : 2;
}
这是带有注释的 MSIL,因此任何人都可以理解所做的工作以及为什么内联语法确实需要隐式转换。
对于内联 if :
.method private hidebysig static void InlineIf(bool condition) cil managed
{
.maxstack 1
.locals init (
[0] int32 i)
L_0000: nop
L_0001: ldarg.0 -- Load argument '0' onto the stack
L_0002: brtrue.s L_0007 -- Branch to L_0007 if value is non-zero
L_0004: ldc.i4.2 -- Push 2 onto the stack
L_0005: br.s L_0008 -- Branch to L_0008
L_0007: ldc.i4.1 -- Push 1 onto the stack
L_0008: nop
L_0009: stloc.0 -- Pop from stack into local variable 0
L_000a: ret
}
这是“正常”的情况,如果:
.method private hidebysig static void ClassicalIf(bool condition) cil managed
{
.maxstack 2
.locals init (
[0] int32 i,
[1] bool CS$4$0000) -- Additional bool for if
L_0000: nop
L_0001: ldc.i4.0 -- Push 0 onto the stack
L_0002: stloc.0 -- Pop from stack into local variable '0'
L_0003: ldarg.0 -- Load argument '0' onto the stack
L_0004: ldc.i4.0 -- Push 0 onto the stack
L_0005: ceq -- Push 1 if value1 equals value2 (on stack), else push 0.
L_0007: stloc.1 -- Pop from stack into local variable '1'
L_0008: ldloc.1 -- Load local variable '1' onto stack.
L_0009: brtrue.s L_000f -- Branch to L_000f if value is non-zero
L_000b: ldc.i4.1 -- Push 1 onto the stack
L_000c: stloc.0 -- Pop from stack into local variable '0'
L_000d: br.s L_0011 -- Branch to L_0011
L_000f: ldc.i4.2 -- Push 2 onto the stack
L_0010: stloc.0 -- Pop from stack into local variable '0'
L_0011: ret
}
因此,如果可能,我也会尝试使用内联。更少的指令(所以 CPU)和更少的内存使用。