2012-02-07 73 views
10

我只是读在C#继承中,我遇到了构造函数和被写了构造函数中派生的顺序执行。这是什么意思?这个基类的构造函数将被称为first或Derived类。订购调用继承的构造情况下,在C#中

+3

是的,基类对象必须在派生类对象之前构造。 – 2012-02-07 05:56:22

回答

15

甲基类构造函数被调用first.Refer以下示例

// 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. 
2

基类的构造将被首先调用。您可以测试这个很容易地自己:

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(); 
     } 
    } 
} 
2

类构造函数的调用由派生隐含的顺序,不过要注意的是,在C#中是很重要的,字段初始化(如int foo=5)的基类的构造函数之前运行,从而以相反的顺序运行。如果基础构造函数可能会导致在派生类中被覆盖的虚拟函数在基础构造函数完成之前被调用,那么这将非常有用。这样的函数将会看到由字段初始化器初始化的任何变量被初始化。

VB.net,顺便说一句,运行所有字段初始化基类的构造完成后,但在派生类的构造任何东西(比链中的其他于基座构造函数)之前。这意味着虚拟方法必须意识到字段初始值设定项可能没有运行,但也意味着字段初始值设定项可以在构造中使用对象(它们在C#中不能这样做)。顺便说一下,在VB.net中,虽然笨重,但类可以用新创建的IDisposable实例安全地初始化字段(并确保如果构建过程的任何部分抛出异常,它们将被丢弃)。在C#中,如果构造抛出异常,必须避免使用字段初始值设定项来创建任何不能安全放弃的内容,因为无法访问部分构建的对象来清除它。

0
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(); 
    } 
} 

这个程序的输出如下:

嘿其父。

嘿它的派生。

构造函数在继承位中的作用不同,让新程序员感到困惑。有在构造 1.呼叫 2.执行 当您创建派生构造函数首先进入派生(命名派生类的一个对象的执行)两个概念然后它去父()因为它的呼叫。 调用的构造函数从Bottom to Top完成,但后来发现它首先执行Parent(),然后是Derived,这是因为它的Execution。 构造函数从顶部到底部执行。这就是为什么它首先打印Parent,然后Base基础构造函数先打印。