关于c#中的System.Object构造函数class

Regarding System.Object Constructor class in c#

对象class构造函数在创建对象时在class的构造函数中调用。对象构造函数中发生了什么?

Reference Source for object中,这是构造函数的代码:

// Creates a new instance of an Object.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public Object()
{            
}

那里没有任何反应。

在评论中,您询问 class 成员如何初始化为其默认值。下面程序中的Main()方法...

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program program = new Program();
        }
    }
}

由编译器翻译成以下 MSIL:

IL_0000:  nop
IL_0001:  newobj     instance void ConsoleApp1.Program::.ctor()
IL_0006:  stloc.0
IL_0007:  ret

这里有趣的指令是 newobj。其中包括:

allocates a new instance of the class associated with ctor and initializes all the fields in the new instance to 0 (of the proper type) or null references as appropriate.

因此 newobj 将所有 class 成员初始化为某种类型的 0null.

在评论中,您询问如果将字段初始化为特定值会发生什么。如果我们修改上面的程序:

namespace ConsoleApp1
{
    class Program
    {
        private int i = 1;

        public Program()
        {
            i = 2;
        }

        static void Main(string[] args)
        {
            Program program = new Program();
        }
    }
}

我们添加了一个初始化为 1 的字段 i 和一个将 i 设置为 2 的构造函数。

Programclass 的构造函数的 MSIL 如下所示:

IL_0000:  ldarg.0
IL_0001:  ldc.i4.1
IL_0002:  stfld      int32 ConsoleApp1.Program::i
IL_0007:  ldarg.0
IL_0008:  call       instance void [mscorlib]System.Object::.ctor()
IL_000d:  nop
IL_000e:  nop
IL_000f:  ldarg.0
IL_0010:  ldc.i4.2
IL_0011:  stfld      int32 ConsoleApp1.Program::i
IL_0016:  ret

所以现在,

  • newobj 创建对象并初始化它的内存(将 i 设置为 0)。
  • Program 运行 和 ldc.i4.1 后跟 stfld ... i 的构造函数将 i 设置为 1
  • 然后基classSystem.Object的构造函数被调用
  • 然后(仍在Program的构造函数中)将i设置为2ldc.i4.2后跟[=​​27=])。

如此有效地 i 设置了 3 次(0、1 和 2)并且当基础 class 运行s i 的构造函数有一个Program 的构造函数完成时的不同值。

关于初始化器和构造器的顺序 运行 请参阅 Eric Lippert 的 these posts