基类构造函数和初始化器的执行顺序
using System;
namespace cSharpJichu
{
public class A
{
public A()
{
Console.WriteLine("A的构造函数被调用");
}
}
public class B : A
{
public B()
{
Console.WriteLine("B的构造函数被调用");
}
X x = new X(); //初始化器
}
public class X
{
public X()
{
Console.WriteLine("X的构造函数调用");
}
}
class test
{
static void Main(string[] args)
{
B b = new B();
Console.Read();
}
}
}
namespace cSharpJichu
{
public class A
{
public A()
{
Console.WriteLine("A的构造函数被调用");
}
}
public class B : A
{
public B()
{
Console.WriteLine("B的构造函数被调用");
}
X x = new X(); //初始化器
}
public class X
{
public X()
{
Console.WriteLine("X的构造函数调用");
}
}
class test
{
static void Main(string[] args)
{
B b = new B();
Console.Read();
}
}
}
运行结果:
原因:构造函数Construcotr ,在实例化New时被自动调用