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

c# virtual作用

作者:冷空气来袭   发布日期:2025-07-17   浏览:100

using System;

public class Animal
{
    // 定义一个虚方法,允许派生类重写此方法
    public virtual void MakeSound()
    {
        Console.WriteLine("The animal makes a sound.");
    }
}

public class Dog : Animal
{
    // 重写基类中的虚方法
    public override void MakeSound()
    {
        Console.WriteLine("The dog barks.");
    }
}

public class Program
{
    public static void Main()
    {
        Animal myAnimal = new Animal();
        Animal myDog = new Dog();

        myAnimal.MakeSound(); // 输出: The animal makes a sound.
        myDog.MakeSound();    // 输出: The dog barks.
    }
}

解释说明:

  1. virtual 关键字:在 Animal 类中,MakeSound 方法被声明为 virtual,这意味着它可以在派生类中被重写。
  2. override 关键字:在 Dog 类中,MakeSound 方法使用 override 关键字来重写基类中的同名方法。
  3. 多态性:通过将 myDog 对象声明为 Animal 类型,但实例化为 Dog 类型,调用 MakeSound 方法时会根据实际对象类型执行相应的方法。这展示了 C# 中的多态特性。

上一篇:c# crc16校验

下一篇:c# checkedlistbox

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# 取字符串最后一个字符

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

Laravel 中文站