C# 继承父类,base指定构造函数

        可以把常用方法定义为基类(子类继承的父类),不同子类支持更多方法或同样函数不同的实现方式,类似接口定义函数后,不同的类实现对应接口函数,根据new对应的类来调用对应的函数执行。

        在C#中,如果子类的构造函数没有显式调用base()(即父类构造函数),那么编译器会自动插入对父类参数less构造函数的调用。这意味着即使子类的构造函数中没有显式的base()调用,父类的无参数构造函数仍然会在子类构造函数之前执行。

以下主要描述几种情况代码:

1、父类只有无参构造函数,子类不用base也会先调用父类构造函数

2、父类构造函数有入参或多个构造函数,子类需要使用base去指向父类对应的构造函数

不用base关键字,示例代码

using System;

class Parent
{
    public Parent()
    {
        Console.WriteLine("Parent constructor called");
    }
}

class Child : Parent
{
    public Child()
    {
        Console.WriteLine("Child constructor called");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Child child = new Child();
    }
}

运行结果

Parent constructor called
Child constructor called

用base关键字,示例代码

using System;

class Parent
{
    public Parent()
    {
        Console.WriteLine("Parent default constructor called");
    }

    public Parent(int value)
    {
        Console.WriteLine($"Parent constructor with parameter called: {value}");
    }
}

class Child : Parent
{
    public Child() : base() // 调用父类的无参数构造函数
    {
        Console.WriteLine("Child default constructor called");
    }

    public Child(int value) : base(value) // 调用父类的带参数构造函数
    {
        Console.WriteLine("Child constructor with parameter called: {0}", value);
    }

    public Child(string value) : base()  // 默认调用父类的带参数构造函数
    {
        Console.WriteLine("Child constructor with parameter called: {0}", value);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Child child1 = new Child();
        Child child2 = new Child(42);
        Child child3 = new Child("hello");
    }
}

运行结果

Parent default constructor called
Child default constructor called
Parent constructor with parameter called: 42
Child constructor with parameter called: 42
Parent default constructor called
Child constructor with parameter called: hello

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值