不在定義的時候初始化字段的值金句,是因為如果有多個構(gòu)造器责鳍,那么il生成代碼的時候會給每一個構(gòu)造器都進行字段初始化忆植。標(biāo)記為const或者static的則不會。
using System;
public class C {
int a=5;
int b=3;
static int mm=5;
const int mmm=4;
public C()
{
}
public C(int a)
{
}
public void M() {
}
}
下面是部分il代碼
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x2050
// Code size 23 (0x17)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldc.i4.5
IL_0002: stfld int32 C::a
IL_0007: ldarg.0
IL_0008: ldc.i4.3
IL_0009: stfld int32 C::b
IL_000e: ldarg.0
IL_000f: call instance void [System.Private.CoreLib]System.Object::.ctor()
IL_0014: nop
IL_0015: nop
IL_0016: ret
} // end of method C::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor (
int32 a
) cil managed
{
// Method begins at RVA 0x2050
// Code size 23 (0x17)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldc.i4.5
IL_0002: stfld int32 C::a
IL_0007: ldarg.0
IL_0008: ldc.i4.3
IL_0009: stfld int32 C::b
IL_000e: ldarg.0
IL_000f: call instance void [System.Private.CoreLib]System.Object::.ctor()
IL_0014: nop
IL_0015: nop
IL_0016: ret
} // end of method C::.ctor