声明更接近其定义位置的变量?C#IL代码不一样

声明更接近其定义位置的变量?C#IL代码不一样,c#,variables,optimization,C#,Variables,Optimization,在C#中,我想知道我们是否应该将varbile clsoer声明到它的使用位置,是的,在同一个问题中有多个问题。但我还是有疑问 我尝试使用如下示例代码: private void button1_Click(object sender, EventArgs e) { for(int i= 0; i<=1000; i++) { int myVariable = 12; myVariable = i; } } /方法Form1的结尾::

在C#中,我想知道我们是否应该将varbile clsoer声明到它的使用位置,是的,在同一个问题中有多个问题。但我还是有疑问

我尝试使用如下示例代码:

private void button1_Click(object sender, EventArgs e)
{
    for(int i= 0; i<=1000; i++)
    {
        int myVariable = 12;
        myVariable = i;
    }
}
/方法Form1的结尾::按钮1\u单击

for循环外的变量:

.method private hidebysig instance void  button1_Click(object sender,
                                                       class [mscorlib]System.EventArgs e) cil managed
{
  // Code size       32 (0x20)
  .maxstack  2
  .locals init ([0] int32 i,
           [1] int32 myVariable,
           [2] bool CS$4$0000)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  IL_0003:  br.s       IL_0010
  IL_0005:  nop
  IL_0006:  ldc.i4.s   12
  IL_0008:  stloc.1
  IL_0009:  ldloc.0
  IL_000a:  stloc.1
  IL_000b:  nop
  IL_000c:  ldloc.0
  IL_000d:  ldc.i4.1
  IL_000e:  add
  IL_000f:  stloc.0
  IL_0010:  ldloc.0
  IL_0011:  ldc.i4     0x3e8
  IL_0016:  cgt
  IL_0018:  ldc.i4.0
  IL_0019:  ceq
  IL_001b:  stloc.2
  IL_001c:  ldloc.2
  IL_001d:  brtrue.s   IL_0005
  IL_001f:  ret
} /
.method private hidebysig instance void  button1_Click(object sender,
                                                       class [mscorlib]System.EventArgs e) cil managed
{
  // Code size       32 (0x20)
  .maxstack  2
  .locals init ([0] int32 myVariable,
           [1] int32 i,
           [2] bool CS$4$0000)
  IL_0000:  nop
  IL_0001:  ldc.i4.s   12
  IL_0003:  stloc.0
  IL_0004:  ldc.i4.0
  IL_0005:  stloc.1
  IL_0006:  br.s       IL_0010
  IL_0008:  nop
  IL_0009:  ldloc.1
  IL_000a:  stloc.0
  IL_000b:  nop
  IL_000c:  ldloc.1
  IL_000d:  ldc.i4.1
  IL_000e:  add
  IL_000f:  stloc.1
  IL_0010:  ldloc.1
  IL_0011:  ldc.i4     0x3e8
  IL_0016:  cgt
  IL_0018:  ldc.i4.0
  IL_0019:  ceq
  IL_001b:  stloc.2
  IL_001c:  ldloc.2
  IL_001d:  brtrue.s   IL_0008
  IL_001f:  ret
} // end of method Form1::button1_Click

良好的实践完全取决于您的需求!如果您需要一个不同的变量,每次循环迭代,您都要在循环内部创建它,否则您应该将它放在外部。

确保您在启用优化的发布模式下编译。@MichaelLiu哇!那真是太不一样了!释放模式下的IL代码看起来完全不同,现在两个代码看起来完全相同。谢谢