基础构造函数的目的是什么 [英] What is the purpose of base constructors
问题描述
在为派生类创建构造函数时调用基础构造函数的目的是什么?
示例:
What is the purpose of calling a base constructor when creating a constructor for a derived class?
Example:
class Manager : Employee
{
public Manager()
:base()
{
}
推荐答案
基础构造函数允许在构造派生类时执行公共初始化代码。 当您想在构造派生类时向其传递参数时,显式调用基础构造函数。 例如:
A base constructor allows common initialization code to be executed when a derived class is constructed. You explicitly call a base constructor when you want to pass arguments to it when the derived class is being constructed. For example:
public class MyException : Exception
{
public MyException
(string message,
object data) : base (message)
{
// Common initialization comes here
...
}
}
/ ravi
在你的例子中没有。在这种情况下,将自动调用Employee
的构造函数。
但是,如果你有一个带参数的构造函数,有一个目的。请考虑以下示例:
In your example none. In this caseEmployee
's constructor will automatically be called.
However, if you have a constructor with parameters, there is a purpose. Consider the following example:
abstract class Foo
{
protected Foo()
{
}
protected Foo(int number)
{
}
protected Foo(string s)
{
}
}
class Bar : Foo
{
public Bar()
{
// Foo() is invoked automatically, since the call to the base constructor is omitted.
}
public Bar(int number)
: base(number)
{
// Foo(int) is called, since it is explicitly invoked
}
public Bar(string s)
{
// Foo() is invoked automatically, since the call to the base constructor is omitted.
}
}
如果 Foo
不有一个默认的构造函数(在我的例子中),它的构造函数需要显式调用。如果你没有在 Bar
上实现 some 构造函数,实际上会出现编译器错误,如果你没有调用基础构造函数,那么也将是一个错误。
底线,如果您的基类中有无参数构造函数,如果您没有明确指定它,它将自动调用。如果你没有无参数构造函数,你有从派生类中调用它,无论你是否需要它。
If Foo
does not have a default constructor (in my example it does), its constructor needs to be explicitly called. There will actually be a compiler error if you don't implement some constructor on Bar
, and if you don't call the base constructor, there will be an error as well.
Bottom line, if you have a parameterless constructor in your base class, it will be automatically called if you don't explicitly specify it. And if you do not have a parameterless constructor, you have to call it from your derived class whether you want it or not.
base constructor用于运行基类方法
base constructor is used for run base class methods
这篇关于基础构造函数的目的是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!