C#构造函数的 "继承" 问题

首先说明下 之所以用 双引号 是因为构造函数是没有继承的

派生类默认会调用基类的无参数构造函数

比如: 

  public class A         {

        public A()         {

            Console.WriteLine("A");

        }

        public A(string name)         {

            Console.WriteLine("A Name:{0}", name);

        }

    }

    public class B : A     {

        public B()         {

            Console.WriteLine("B");

        }

        public B(string name)         {

            Console.WriteLine("B Name:{0}", name);

        }

    }

class Program

{

  static void Main(string[] args)

  {

    B b = new B();
            B b1 = new B("张三");
            Console.ReadKey();

  }

}

输出的结果为:

说明不管调用派生类的哪个构造函数,默认都先调用基类的无参数构造函数

之所以标题中用 "继承" 是因为构造函数之间的调用也是用 ":",下面就在派生类里面调用一下基类的构造函数

class Program     {        

   static void Main(string[] args)        

   {            

    B b = new B();            

     Console.ReadKey();        

  }

    }

public class B : A     {

        public B():base("B->A")         {

            Console.WriteLine("B");

        }

        public B(string name)         {

            Console.WriteLine("B Name:{0}", name);

        }

    }

输出结构为:

由结果可以看出,当给B的构造函数手动指派要调用的基类带参数的构造函数后,将不再执行基类的无参数构造函数

下面写下在同一个类中构造函数的调用

class Program     {       

   static void Main(string[] args)       

   {            

    B b = new B();           

     Console.ReadKey();        

  }

    }

public class B : A     {

        public B():this("无惨->带参")         {

            Console.WriteLine("B");

        }

        public B(string name):this(true)         {

            Console.WriteLine("B Name:{0}", name);

        }        

  public B(bool b)         {            

     Console.WriteLine("B bool:{0}", b);         }    

  }

输出结果:

为了看一下调用的先后关系就又加了一个bool参数的构造函数,由结果可以看出如果构造函数调用了另一个构造函数,例如:

public B():this("无惨->带参")        

执行顺序是从后向前依次执行的

没有困难创造困难也要上!
原文地址:https://www.cnblogs.com/tiaf/p/3360932.html