可以说我们编译下面的代码,在优化的释放&构建
namespace ConsoleApplication4
{
public class Test1
{
private int myIntToInitalize;
public Test1()
{
myIntToInitalize = 10;
}
}
public class Test2
{
private int myIntToInitalize = 10;
}
static class Program
{
private static void Main()
{
}
}
}
的IL指令为类测试1
.class public auto ansi beforefieldinit Test1
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
.maxstack 8
L_0000: ldarg.0
L_0001: call instance void [mscorlib]System.Object::.ctor()
L_0006: ldarg.0
L_0007: ldc.i4.s 10
L_0009: stfld int32 ConsoleApplication4.Test1::myIntToInitalize
L_000e: ret
}
.field private int32 myIntToInitalize
}
的IL指令类的Test2
.class public auto ansi beforefieldinit Test2
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
.maxstack 8
L_0000: ldarg.0
L_0001: ldc.i4.s 10
L_0003: stfld int32 ConsoleApplication4.Test2::myIntToInitalize
L_0008: ldarg.0
L_0009: call instance void [mscorlib]System.Object::.ctor()
L_000e: ret
}
.field private int32 myIntToInitalize
}
非常明显,两个类都有相同数量的IL插入唯一的区别是,
变量在调用Class Test1中的:: ctor()之前被初始化; 和 变量在Class Test2中调用:: ctor()后被初始化;
注意:性能方面既可使用类将执行相同的,因为他们有相同的数字&型IL指令,只是IL指令的执行顺序是不同
可能的复制,HTTP://计算器。 com/questions/24551/best-practice-initialize-class-fields-in-constructor-or-at-declaration and http://stackoverflow.com/questions/298183/c-sharp-member-variable-initialization-best-练习 – Cyral
http://stackoverflow.com/a/14083981/922198 –