class Person
{
public int age;
public Person()
{
age = 1;
}
}
class Customer : Person
{
public Customer()
{
age += 1;
}
}
Customer customer = new Customer();
客户年龄为2岁?看来无论如何都将调用基类的构造函数。如果是这样,为什么base
有时需要在最后打个电话呢?
public Customer() : base()
{
.............
}
这就是C#的工作方式。类型层次结构中每种类型的构造函数将按照“最基本->最派生”的顺序进行调用。
因此,在您的特定实例中,它调用Person()
,然后Customer()
在构造函数中调用。有时需要使用base
构造函数的原因是,当前类型下方的构造函数需要其他参数。例如:
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
实现来实现。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句