C# 属性

C# 抽象

C# 字符串

C# 泛型

C# 杂项

C# 新特性

C# 多态性

术语“多态性”是“poly”+“morphs”的组合,表示多种形式。这是一个希腊词。在面向对象编程中,我们使用 3 个主要概念:继承、封装和多态。

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

C# 运行时多态性示例

让我们看一个 C# 中运行时多态的简单示例。

例子 (Example)

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

输出:

吃面包...

C# 运行时多态示例 2

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

例子 (Example)

using System;  
public class Shape{  
    public virtual void draw(){  
        Console.WriteLine("绘图...");  
    }  
}  
public class Rectangle: Shape  
{  
    public override void draw()  
    {  
        Console.WriteLine("绘制矩形...");  
    }  
      
}  
public class Circle : Shape  
{  
    public override void draw()  
    {  
        Console.WriteLine("画圈...");  
    }  
  
}  
public class TestPolymorphism  
{  
    public static void Main()  
    {  
        Shape s;  
        s = new Shape();  
        s.draw();  
        s = new Rectangle();  
        s.draw();  
        s = new Circle();  
        s.draw();  
  
    }  
}

输出:

画画...
绘制矩形...
画圈...

具有数据成员的运行时多态性

C# 中的数据成员无法实现运行时多态性。让我们看一个示例,我们通过引用变量访问字段,该变量引用派生类的实例。

例子 (Example)

using System;  
public class Animal{  
    public string color = "白色的";  
  
}  
public class Dog: Animal  
{  
    public string color = "黑色的";  
}  
public class TestSealed  
{  
    public static void Main()  
    {  
        Animal d = new Dog();  
        Console.WriteLine(d.color);  
    
    }  
}

输出:

白色的


上一主题 C# 基础 下一主题 C# 密封
  • 使用社交账号登录,本站支持
全部评论(0)