我有一个基类 Character,它有几个派生自它的类。基类有各种字段和方法。
我所有的派生类都使用相同的基类构造函数,但如果我不在派生类中重新定义构造函数,我会得到错误:
错误:“子类”类不包含采用此数量参数的构造函数
我不想在每个派生类中重新定义构造函数,因为如果构造函数更改,我必须在每个类中更改它,请原谅任何误解,这与只编写一次代码的想法背道而驰?
最佳答案
您可以使用以下语法从派生类调用基类构造函数:
public DerivedClass() : base() {
// Do additional work here otherwise you can leave it empty
}
这将首先调用基本构造函数,然后它将在派生构造函数中执行任何其他语句(如果有的话)。
请注意,如果基础构造函数接受参数,您可以这样做:
public DerivedClass(int parameter1, string parameter2)
: base(parameter1, parameter2) {
// DerivedClass parameter types have to match base class types
// Do additional work here otherwise you can leave it empty
}
您可以在以下页面中找到有关构造函数的更多信息:
In a derived class, if a base-class constructor is not called explicitly by using the
base
keyword, the default constructor, if there is one, is called implicitly.
关于C# - 使所有派生类调用基类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4296888/