问题描述
class Person
{
public int age;
public Person()
{
age = 1;
}
}
class Customer : Person
{
public Customer()
{
age += 1;
}
}
Customer customer = new Customer();
客户的年龄是 2 岁吗?似乎无论如何都会调用基类的构造函数.如果是这样,为什么有时我们需要在最后调用base
?
Would the age of customer be 2? It seems like the base class's constructor will be called no matter what. If so, why do we need to call base
at the end sometimes?
public Customer() : base()
{
.............
}
推荐答案
这就是 C# 的工作方式.类型层次结构中每种类型的构造函数将按照 Most Base -> Most Derived 的顺序调用.
This is simply how C# is going to work. The constructors for each type in the type hierarchy will be called in the order of Most Base -> Most Derived.
因此,在您的特定实例中,它会在构造函数顺序中调用 Person()
,然后调用 Customer()
.有时需要使用 base
构造函数的原因是当前类型下面的构造函数需要额外的参数.例如:
So in your particular instance, it calls Person()
, and then Customer()
in the constructor orders. The reason why you need to sometimes use the base
constructor is when the constructors below the current type need additional parameters. For example:
public class Base
{
public int SomeNumber { get; set; }
public Base(int someNumber)
{
SomeNumber = someNumber;
}
}
public class AlwaysThreeDerived : Base
{
public AlwaysThreeDerived()
: base(3)
{
}
}
为了构造一个 AlwaysThreeDerived
对象,它有一个无参数的构造函数.但是,Base
类型没有.因此,为了创建无参数构造函数,您需要为基础构造函数提供一个参数,您可以通过 base
实现来实现.
In order to construct an AlwaysThreeDerived
object, it has a parameterless constructor. However, the Base
type does not. So in order to create a parametersless constructor, you need to provide an argument to the base constuctor, which you can do with the base
implementation.
这篇关于会自动调用基类构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!