1.前言
RT:有人问Net里面的.CCtor和Ctor是什么?首先说答案,.CCtor是静态构造函数,.Ctor是非静态构造函数。通过例子分析下这两个特殊的函数,本篇看下。
2.概述
先上例子:
public class ABC{
public ABC(){
}
int i=0x10;
}
public class BBC:ABC{
public BBC(){
}
int i = 0x20;
}
static void Main(string[] args)
{
BBC bBC = new BBC();
}
简单点来说,类BBC的非静态构造函数就是BBC.Ctor,也就是构造函数BBC(){}.同理ABC的非静态构造函数ABC.Ctor也就是ABC(){}
作用为什么Roslyn编译器要加上一个这种函数,就是为了循环往上初始化父类。直到Object.Ctor为止,也就是初始化到最基础的Object类为止才不会初始化,一层层的向上执行。
以上面例子为例
运行的过程如下:
1.new BBC()
2.BBC.Ctor
3.ABC.Ctor
4.Object.Ctor
也就是说,有多少个父类,它统统初始化。方便以后调用,比如ABC类里面有个变量i,就是此时被初始化的,如果没有被初始化,如果需要用到就会报错。这里注意,如果BBC类里面有全局变量,则优先于ABC里面的全局变量i初始化。
代码最后我们看下它的底层代码BBC bBC = new BBC() Program+BBC..ctor
00007FF862D006D7 48 B9 50 21 DF 62 F8 7F 00 00 mov rcx,7FF862DF2150h
00007FF862D006E1 E8 7A 02 B0 5F call CORINFO_HELP_NEWSFAST (07FF8C2800960h)
00007FF862D006E6 48 89 45 20 mov qword ptr [rbp+20h],rax
00007FF862D006EA 48 8B 4D 20 mov rcx,qword ptr [rbp+20h]
00007FF862D006EE E8 05 E7 0D 00 call Test_.Program+BBC..ctor() (07FF862DDEDF8h)
int i=0x10 public ABC(){}
00007FF862D015C7 E8 44 64 C2 5F call 00007FF8C2927A10
00007FF862D015CC 48 8B 4D 40 mov rcx,qword ptr [rbp+40h]
00007FF862D015D0 C7 41 08 10 00 00 00 mov dword ptr [rcx+8],10h
00007FF862D015D7 48 8B 4D 40 mov rcx,qword ptr [rbp+40h]
00007FF862D015DB FF 15 4F FA F6 FF call qword ptr [CLRStub[MethodDescPrestub]@00007FF862C71030 (07FF862C71030h)]
00007FF862D015E1 90 nop
00007FF862D015E2 90 nop
00007FF862D015E3 FF 15 2F 63 12 00 call qword ptr [CLRStub[MethodDescPrestub]@00007FF862E27918 (07FF862E27918h)]
public BBC(){}
00007FF862D0157B E8 60 D8 0D 00 call Test_.Program+ABC..ctor() (07FF862DDEDE0h)
00007FF862D01580 90 nop
00007FF862D01581 90 nop