繁体   English   中英

从父类到子类执行构造函数

[英]Executing constructor from Parent class to Child class

在什么情况下我应该为子类执行父类的构造函数? 为什么使用“base”保留字?

例子:

在此处输入图片说明

在此处输入图片说明

如果您不使用 :base 字作为子构造函数。

将执行 parent 的默认构造函数。

如果您在基类中有一些基本的构造函数并且其中有一些字段并想使用基本构造函数填充它,则应使用 base 关键字。

基类的构造函数总是被调用。 或者更准确地说,是基类的一个构造函数。 如果不指定哪一个(通过使用base保留字),则调用基类的默认构造函数(即没有参数的构造函数)。 如果基类没有没有参数的构造函数,则会发生编译器错误。 使用base关键字,您可以指定要调用某个构造函数。 下面是一些简单的例子:

public class Base 
{
    private int _a;
    public Base() // default ctor
    {_a = 0;}
    public Base(int a) // a ctor with an argument
    {_a = a;}
}

public class Derived : Base
{
    public Derived() : base(2) // call the ctor with argument "2"
    {}
    public Derived(bool b) // uses the ctor without argument of the base class (_a will stay 0)
    {
    }
}

此处的关键字base用作基类名称的通用占位符。 语法上允许的唯一另一个词是this (如果你想调用同一个类的构造函数)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM