调用构造函数的顺序c#中的inheritance情况

我只是在C#中读取inheritance,其中我遇到了构造函数,并且编写了构造函数按派生顺序执行。 它是什么意思?将首先调用该基类构造函数或派生类。

首先调用基类构造函数。参见以下示例

// Demonstrate when constructors are called. using System; // Create a base class. class A { public A() { Console.WriteLine("Constructing A."); } } // Create a class derived from A. class B : A { public B() { Console.WriteLine("Constructing B."); } } // Create a class derived from B. class C : B { public C() { Console.WriteLine("Constructing C."); } } class OrderOfConstruction { static void Main() { C c = new C(); } } The output from this program is shown here: Constructing A. Constructing B. Constructing C. 

类构造函数按派生所暗示的顺序调用,但重要的是要注意在C#中,字段初始值设定项(例如int foo=5 )在基类构造函数之前运行,因此以相反的顺序运行。 如果基础构造函数可能导致在基础构造函数完成之前调用派生类中被覆盖的虚函数,则这非常有用。 这样的函数将看到由字段初始化程序初始化的任何变量已经初始化。

顺便提一下,VB.net在基类构造函数完成之后运行所有字段初始值设定项,但在派生类构造函数中的任何内容之前(除了基本构造函数的链之外)。 这意味着虚方法必须知道字段初始值设定项可能没有运行,但也意味着字段初始值设定项可以使用构造下的对象(它们在C#中无法做到)。

顺便提一下,在VB.net中,尽管很笨重,但是可以使用新创建的IDisposable实例来安全地初始化字段(并确保在构造过程的任何部分抛出exception时它们将被处置)。 在C#中,必须避免使用字段初始化程序来创建在构造抛出exception时无法安全放弃的任何内容,因为无法访问部分构造的对象来清理它。

将首先调用基类构造函数。 您可以自己轻松测试:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DerivationTest { class Program { public class Thing { public Thing() { Console.WriteLine("Thing"); } } public class ThingChild : Thing { public ThingChild() { Console.WriteLine("ThingChild"); } } static void Main(string[] args) { var tc = new ThingChild(); Console.ReadLine(); } } } 
 using System; class Parent { public Parent () { Console.WriteLine("Hey Its Parent."); } } class Derived : Parent { public Derived () { Console.WriteLine("Hey Its Derived."); } } class OrderOfExecution { static void Main() { Derived obj = new Derived(); } } 

此程序的输出如下所示:

嘿它的父母。

嘿它的衍生。

对于新程序员而言,构造函数在inheritance位中的作用有所不同。 构造函数1的执行有两个概念。调用2.执行当你创建派生类的对象Named Derived时,构造函数首先转到Derived()然后由于它的调用而转到Parent()构造函数调用是从Bottom到Top完成的,但是你会发现它先执行Parent()然后是Derived,这是因为它的执行。 构建器从上到下执行 。 这就是为什么它首先打印Parent然后是Base而基本构造函数首先打印。