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
相关推荐
架构文摘JGWZ25 分钟前
Java 23 的12 个新特性!!
java·开发语言·学习
leon62526 分钟前
优化算法(一)—遗传算法(Genetic Algorithm)附MATLAB程序
开发语言·算法·matlab
锦亦之22331 小时前
QT+OSG+OSG-earth如何在窗口显示一个地球
开发语言·qt
我是苏苏1 小时前
Web开发:ABP框架2——入门级别的增删改查Demo
java·开发语言
姜太公钓鲸2331 小时前
c++ static(详解)
开发语言·c++
菜菜想进步1 小时前
内存管理(C++版)
c语言·开发语言·c++
2301_789985942 小时前
Java语言程序设计基础篇_编程练习题*18.29(某个目录下的文件数目)
java·开发语言·学习
知星小度S2 小时前
C语言——自定义类型
c语言·开发语言
__water2 小时前
『功能项目』回调函数处理死亡【54】
c#·回调函数·unity引擎
__water2 小时前
『功能项目』眩晕图标显示【52】
c#·unity引擎·动画事件