Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# base

作者:黑白灰调   发布日期:2025-10-06   浏览:33

// 示例代码:使用 base 关键字调用基类的构造函数和方法

using System;

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

    public virtual void MakeSound()
    {
        Console.WriteLine("Animal makes a sound");
    }
}

public class Dog : Animal
{
    public Dog() : base() // 调用基类 Animal 的构造函数
    {
        Console.WriteLine("Dog constructor");
    }

    public override void MakeSound()
    {
        base.MakeSound(); // 调用基类 Animal 的 MakeSound 方法
        Console.WriteLine("Dog barks");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dog myDog = new Dog();
        myDog.MakeSound();
    }
}

解释说明:

  1. base():在派生类 Dog 的构造函数中,通过 : base() 显式调用基类 Animal 的构造函数。这确保了在创建 Dog 对象时,先初始化基类 Animal

  2. base.MakeSound():在 Dog 类的 MakeSound 方法中,使用 base.MakeSound() 来调用基类 Animal 中的 MakeSound 方法。这样可以在重写的方法中仍然保留基类的行为,并在此基础上添加新的行为。

  3. 输出结果

    • 当创建 Dog 对象时,首先输出 Animal constructor,然后输出 Dog constructor
    • 调用 MakeSound 时,先输出 Animal makes a sound,再输出 Dog barks

上一篇:c# 输出

下一篇:c#字符串转int

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

c# rectangle

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站