4

语句在编译成 IL 时是什么if样子的?

这是 C# 中一个非常简单的构造。有人能给我一个更抽象的定义吗?

4

4 回答 4

11

以下是一些if陈述以及它们如何转化为 IL:

ldc.i4.s 0x2f                      var i = 47;
stloc.0 

ldloc.0                            if (i == 47)
ldc.i4.s 0x2f
bne.un.s L_0012

ldstr "forty-seven!"                   Console.WriteLine("forty-seven!");
call Console::WriteLine

L_0012:
ldloc.0                            if (i > 0)
ldc.i4.0 
ble.s L_0020

ldstr "greater than zero!"             Console.WriteLine("greater than zero!");
call Console::WriteLine

L_0020:
ldloc.0                            bool b = (i != 0);
ldc.i4.0 
ceq 
ldc.i4.0 
ceq 
stloc.1 

ldloc.1                            if (b)
brfalse.s L_0035

ldstr "boolean true!"                  Console.WriteLine("boolean true!");
call Console::WriteLine

L_0035:
ret

这里要注意一件事:IL 指令总是“相反的”。if (i > 0)翻译成有效的意思是“如果i <= 0,则跳过if块体”。

于 2010-09-07T23:33:20.920 回答
5

使用分支指令,该指令将根据堆栈顶部的值跳转到目标指令。

brfalse Branch to target if value is zero (false)
brtrue  Branch to target if value is non-zero (true)
beq     Branch to target if equal
bge     Branch to target if greater than or equal to
bgt     Branch to target if greater than
ble     Branch to target if less than or equal to
blt     Branch to target if less than
bne.un  Branch to target if unequal or unordered
于 2010-09-07T23:40:17.673 回答
4

这取决于if. 例如,如果您正在检查对null编译器的引用,则会发出一条brfalse指令(或brtrue取决于您编写的内容)。

实际 if情况会根据情况本身而有所不同,但像或ILDASMReflector 这样的反汇编程序将是学习更多信息的更好工具。

于 2010-09-07T23:24:10.633 回答
2

一个简单的例子:

ldloc.1                    // loads first local variable to stack
ldc.i4.0                   // loads constant 0 to stack
beq                        // branch if equal

这将等于

if(i == 0) //if i is the first local variable

其他 if 会有所不同,包括条件分支。这真的太多了,无法在一篇文章中解释,您最好寻找 IL-Code 的介绍。

有一篇关于codeproject的好文章与此有关。

于 2010-09-07T23:29:36.403 回答