本文介绍了C#中调用构造函数的继承顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在阅读C#中的继承,在那儿我遇到了构造函数,并写道构造函数是按照派生顺序执行的。是什么意思?基类构造函数将被称为first或派生类。

I was just reading Inheritance in C# in which i came across the Constructors and was written that constructors are executed in order of derivation. What does it mean?That base class constructor will be called first or Derived class.

推荐答案

首先调用基类的构造方法。请参见下面的示例

A base class Constructor is called first.Refer to the following example

// 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#中调用构造函数的继承顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 20:00