无参数构造函数中的第一个参数是什么?

时间:2017-02-08 08:10:38

标签: c# constructor cil

我有这样简单的程序:

public class Foo
{
    public Foo()
    {
    }
    public int MyInt { get; set; } = 10;
    public List<int> MyList { get; set; } = new List<int>();
}

public class Program
{
    static public void Main()
    {
        Console.WriteLine(new Foo().MyInt);
        Console.ReadLine();
    }
}

我决定看看这个程序的CIL代码(我对Foo的构造函数感兴趣)。这是它:

.method public hidebysig specialname rtspecialname
        instance void  .ctor() cil managed
{
    // Code size       26 (0x1a)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  ldc.i4.s   10
    IL_0003:  stfld      int32 Foo::'<MyInt>k__BackingField'
    IL_0008:  ldarg.0
    IL_0009:  newobj     instance void class [mscorlib]System.Collections.Generic.List`1<int32>::.ctor()
    IL_000e:  stfld      class [mscorlib]System.Collections.Generic.List`1<int32> Foo::'<MyList>k__BackingField'
    IL_0013:  ldarg.0
    IL_0014:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0019:  ret
} // end of method Foo::.ctor

我想知道,当我看到第二行ldarg.0时,它是什么意思? this指针?但该对象尚未创建。我该如何修改其成员?我的假设是在调用构造函数之前,clr首先为对象分配内存。然后将成员初始化为默认值,然后调用构造函数。对象调用的最后一个有趣的时刻。我认为这将是第一次。

3 个答案:

答案 0 :(得分:10)

字段初始值设定项是C#功能,而不是CLR功能。编写字段初始值设定项时,C#编译器必须将代码放在某处中,并将其放在任何构造函数体内。

由于这些初始化程序在&#34;之前运行。构造函数,这就是为什么以后运行实际的基类构造函数。

(是的,是的,第一个参数是您推断的,this

答案 1 :(得分:3)

虽然没有创建对象&#39;在构造函数调用之前的最严格意义上,必须为它分配一些内存。我不知道细节,但我猜测类的所有实例方法都有一个隐含的第一个参数,即this;这对于构造函数也是如此,因为它需要像任何其他实例方法一样引用对象实例。

答案 2 :(得分:3)

http://www.philosophicalgeek.com/2014/09/29/digging-into-net-object-allocation-fundamentals/

根据上面的文章,CLR在调用构造函数之前首先分配内存,就像在C ++中对象构造一样。

相关问题