不在定义的时候初始化字段的值,是因为如果有多个构造器,那么il生成代码的时候会给每一个构造器都进行字段初始化。标记为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