using System;
using System.Collections.Generic;
using System.Text;
namespace IL_Learn
...{
class Program
...{
static void Main(string[] args)
...{
int a = 1;
int b = 2;
float c;
c = a + b;
float d = 0;
d = a + b + c;
}
}
}编译后ildasm /adv一下,得到:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 24 (0x18)
.maxstack 2
.locals init (int32 V_0,
int32 V_1,
float32 V_2,
float32 V_3)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.1
IL_0005: ldloc.0
IL_0006: ldloc.1
IL_0007: add
IL_0008: conv.r4
IL_0009: stloc.2
IL_000a: ldc.r4 0.0
IL_000f: stloc.3
IL_0010: ldloc.0
IL_0011: ldloc.1
IL_0012: add
IL_0013: conv.r4
IL_0014: ldloc.2
IL_0015: add
IL_0016: stloc.3
IL_0017: ret
} // end of method Program::Main

原来,每次要进行类型转换,都有csc产生的conv.r4,意思是将栈顶的一个家伙转型为float型,哎,CLR懒死了,连这条指令都由CSC产生!不过,这样,把尽量多的工作交给编译器完成,CLR只是简单的JIT和执行,从而保证了效率。还是应该佩服一下的。
本文通过一个简单的C#示例,展示了CLR在处理类型转换时的工作原理。具体分析了编译器如何生成中间语言来实现整数到浮点数的转换。
2732

被折叠的 条评论
为什么被折叠?



