C#继承和默认构造函数 [英] C# inheritance and default constructors

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

问题描述

假设有一个基类A和一个从A派生的类B. 然后,我们知道类A的构造函数永远不会被类B继承.但是,当创建B的新对象时,-在调用类B的默认/自定义构造函数之前,将调用类A的默认构造函数.也许这样做的目的是需要将A类的字段初始化为默认值.

Suppose there is a base class A and a class B derived from A. Then, we know that the constructor of class A is never inherited by class B. However, when a new object of B is created, then - the default constructor of the class A is called prior to the default/custom constructor of class B is invoked. Maybe the purpose of this is that the fields of class A need to be initialized to default values.

现在,假设类A已定义了一个自定义构造函数.这意味着编译器将静默删除类A的默认构造函数.现在,在创建类B的新实例时,在调用类B的构造函数之前会自动调用哪个类A的构造函数? (在这种情况下,如何初始化A类字段?)

Now, suppose that class A has defined a custom constructor. This means that the default constructor of class A is silently removed by the compiler. Now, on creating a new instance of class B, which constructor of class A is automatically called before invoking the class B's constructor? (How does the class A fields get initialized in such a case?)

推荐答案

现在,在创建类B的新实例时,在调用类B构造函数之前会自动调用哪个类A的构造函数?

Now, on creating a new instance of class B, which constructor of class A is automatically called before invoking the class B constructor?

基本上,代码将无法编译.每个构造函数都必须隐式或显式链接到另一个构造函数.链接到的构造函数可以在同一类(使用this)或基类(使用base)中.

The code will fail to compile, basically. Each constructor has to chain to another constructor, either implicitly or explicitly. The constructor it chains to can be in the same class (with this) or the base class (with base).

这样的构造函数:

public B() {}

是隐式的:

public B() : base() {}

...,如果您根本不指定构造函数,则将以相同的方式隐式添加它-但是它仍然必须要调用一些内容.因此,例如,您的方案:

... and if you don't specify a constructor at all, it will be implicitly added in the same way - but it still has to have something to call. So for example, your scenario:

public class A
{
    public A(int x) {}
}

public class B : A {}

导致编译器错误:

错误CS7036:没有给出与'A.A(int)'

但是,您可以显式指定其他构造函数调用,例如

However, you can specify a different constructor call explicitly, e.g.

public B() : base(10) {} // Chain to base class constructor

public B() : this(10) {} // Chain to same class constructor, assuming one exists

这篇关于C#继承和默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆