C#代码:
public int LoopTest()
{
int s=0;
int[] array={2,3,4,5,6,7,8,9};
for(int k=0;k<=7;k++)
{
s+=array[k];
}
foreach(int a in array)
{
s+=a;
}
return s;
}
IL代码:
.method public hidebysig instance int32 LoopTest() cil managed
{
// 代码大小 78 (0x4e)
.maxstack 3
.locals init ([0] int32 s,
[1] int32[] 'array',
[2] int32 k,
[3] int32 a,
[4] int32 CS$00000003$00000000,
[5] int32[] CS$00000007$00000001,
[6] int32 CS$00000008$00000002)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldc.i4.8
IL_0003: newarr [mscorlib]System.Int32
IL_0008: dup
IL_0009: ldtoken field valuetype '
1<privateimplementationdetails>'/'$$struct0x6000002-1' '<privateimplementationdetails>'::'$$method0x6000002-1'
2IL_000e: call void [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array,
3valuetype [mscorlib]System.RuntimeFieldHandle)
4IL_0013: stloc.1
5IL_0014: ldc.i4.0
6IL_0015: stloc.2
7IL_0016: br.s IL_0022 //for 开始的地方
8IL_0018: ldloc.0
9IL_0019: ldloc.1
10IL_001a: ldloc.2
11IL_001b: ldelem.i4
12IL_001c: add
13IL_001d: stloc.0
14IL_001e: ldloc.2
15IL_001f: ldc.i4.1
16IL_0020: add
17IL_0021: stloc.2
18IL_0022: ldloc.2
19IL_0023: ldc.i4.7
20IL_0024: ble.s IL_0018 //for 结束的地方
21IL_0026: ldloc.1 //foreach 从这里开始
22IL_0027: stloc.s CS$00000007$00000001
23IL_0029: ldc.i4.0
24IL_002a: stloc.s CS$00000008$00000002
25IL_002c: br.s IL_003e
26IL_002e: ldloc.s CS$00000007$00000001
27IL_0030: ldloc.s CS$00000008$00000002
28IL_0032: ldelem.i4
29IL_0033: stloc.3
30IL_0034: ldloc.0
31IL_0035: ldloc.3
32IL_0036: add
33IL_0037: stloc.0
34IL_0038: ldloc.s CS$00000008$00000002
35IL_003a: ldc.i4.1
36IL_003b: add
37IL_003c: stloc.s CS$00000008$00000002
38IL_003e: ldloc.s CS$00000008$00000002
39IL_0040: ldloc.s CS$00000007$00000001
40IL_0042: ldlen
41IL_0043: conv.i4
42IL_0044: blt.s IL_002e //foreach结束的地方
43IL_0046: ldloc.0
44IL_0047: stloc.s CS$00000003$00000000 //此乃自动生成的一个变量,保存返回值,void时没有
45IL_0049: br.s IL_004b
46IL_004b: ldloc.s CS$00000003$00000000
47IL_004d: ret
48} // end of method Class1::LoopTest</privateimplementationdetails></privateimplementationdetails>