代码一:
int i;
for (i = 0; i < 3; i++)
{
}
Console.WriteLine(i); // 正常
代码二:
for (int i = 0; i < 3; i++)
{
}
// Console.WriteLine(i); 变量i超出作用范围
上面两段代码生成的IL代码如下:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 20 (0x14)
.maxstack 2
.locals init ([0] int32 i,
[1] bool CS$4$0000)
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: stloc.0
IL_0003: br.s IL_000b
IL_0005: nop
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: add
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldc.i4.3
IL_000d: clt
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: brtrue.s IL_0005
IL_0013: ret
} // end of method Program::Main
因为生成的IL代码是一模一样的,所以只贴出完整的一段,不能理解的是在这样一段相同的IL代码中,CLR究竟是如何确定变量i的作用域的呢?请教大家了:)