C#多态

C#多态 首页 / C#入门教程 / C#多态

C#中有两种类型的多态性:编译时多态性和运行时多态性。编译时多态性是通过C#中的方法重载和运算符重载来实现的。它也被称为Static静态绑定或早期绑定。运行时多态性是通过方法覆盖实现的,也称为动态绑定或后期绑定。

C#运行时多态性示例

让无涯教程看一个简单的C#运行时多态性示例。

using System;
public class Animal{
    public virtual void eat(){
        Console.WriteLine("eating...");
    }
}
public class Dog: Animal
{
    public override void eat()
    {
        Console.WriteLine("eating bread...");
    }
    
}
public class TestPolymorphism
{
    public static void Main()
    {
        Animal a= new Dog();
        a.eat();
    }
}

输出:

无涯教程网

eating bread...

C#运行时多态性示例 2

让无涯教程看看C#中运行时多态性的另一个示例,其中有两个派生类。

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-polymorphism.html

来源:LearnFk无涯教程网

using System;
public class Shape{
    public virtual void draw(){
        Console.WriteLine("drawing...");
    }
}
public class Rectangle: Shape
{
    public override void draw()
    {
        Console.WriteLine("drawing rectangle...");
    }
    
}
public class Circle : Shape
{
    public override void draw()
    {
        Console.WriteLine("drawing circle...");
    }

}
public class TestPolymorphism
{
    public static void Main()
    {
        Shape s;
        s = new Shape();
        s.draw();
        s = new Rectangle();
        s.draw();
        s = new Circle();
        s.draw();

    }
}

输出:

无涯教程网

drawing...
drawing rectangle...
drawing circle...

C#中的数据成员不能实现运行时多态性。让无涯教程看一个示例,其中通过引用变量访问字段,引用变量引用派生类的实例。

using System;
public class Animal{
    public string color = "white";

}
public class Dog: Animal
{
    public string color = "black";
}
public class TestSealed
{
    public static void Main()
    {
        Animal d = new Dog();
        Console.WriteLine(d.color);
  
    }
}

输出:

无涯教程网

white

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

结构写作力 -〔李忠秋〕

HarmonyOS快速入门与实战 -〔QCon+案例研习社〕

程序员的测试课 -〔郑晔〕

说透区块链 -〔自游〕

说透芯片 -〔邵巍〕

爆款文案修炼手册 -〔乐剑峰〕

Selenium自动化测试实战 -〔郭宏志〕

SRE实战手册 -〔赵成〕

编译原理之美 -〔宫文学〕

好记忆不如烂笔头。留下您的足迹吧 :)