// 示例代码:使用 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();
}
}
base():在派生类 Dog 的构造函数中,通过 : base() 显式调用基类 Animal 的构造函数。这确保了在创建 Dog 对象时,先初始化基类 Animal。
base.MakeSound():在 Dog 类的 MakeSound 方法中,使用 base.MakeSound() 来调用基类 Animal 中的 MakeSound 方法。这样可以在重写的方法中仍然保留基类的行为,并在此基础上添加新的行为。
输出结果:
Dog 对象时,首先输出 Animal constructor,然后输出 Dog constructor。MakeSound 时,先输出 Animal makes a sound,再输出 Dog barks。上一篇:c# 输出
下一篇:c#字符串转int
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站