继承和默认构造函数

继承和默认构造函数

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

问题描述

假设有一个基类 A 和一个从 A 派生的类 B.然后,我们知道A 类的构造函数永远不会被B 类继承.但是,当创建 B 的新对象时, - 类 A 的默认构造函数在类 B 被调用.可能这样做的目的是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?)

推荐答案

代码将无法编译,基本上.每个构造函数都必须隐式或显式地链接到另一个构造函数.它链接的构造函数可以在同一个类中(使用 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# 继承和默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:23