1、介绍

1.1 什么是多态

在C#中,多态性(Polymorphism)是面向对象编程中的一个重要概念,它允许不同类的对象对同一消息做出响应,即同一个方法可以在不同的对象上产生不同的行为。C#中的多态性可以通过以下几种方式实现:

1.2 为什么需要多态

多态性能够提高代码的灵活性和可扩展性,使得程序可以更轻松地适应不同的需求和情境。在C#中,这种特性有助于编写更具有组织性和可维护性的代码

2、实现方式

2.1 方法重载

2.1.1 什么是方法重载

在同一个类中定义多个方法,它们具有相同的名称但具有不同的参数列表。编译器会根据方法参数的类型、顺序和数量来区分调用不同的方法。

2.2 实例

创建MyClass.cs

using System;using System.Collections.Generic;using System.Text;namespace Polymorphism{class MyClass{public void DoSomething(int num){Console.WriteLine($"我是DoSomething之我接受的是int类型的参数:{num}");}public void DoSomething(string text){Console.WriteLine($"我是DoSomething之我接受的是string类型的参数:{text}");}}}

运行效果

2.2 方法重写

2.2.1 概念

在继承关系中,子类可以重写(覆盖)父类的虚方法或抽象方法,以实现特定于子类的行为。

2.2.2 实例

创建Animal.cs

using System;using System.Collections.Generic;using System.Text;namespace Polymorphism{class Animal{public virtual void MakeSound(){Console.WriteLine("我能发出声音。");}}class Dog : Animal{public override void MakeSound(){Console.WriteLine("汪汪汪...");}}class Cat : Animal{public override void MakeSound(){Console.WriteLine("喵喵喵...");}}}

运行结果

2.3 接口

2.3.1 概念

接口定义了一组方法、属性和事件的契约,类可以实现一个或多个接口。通过接口,不同的类可以共享相同的行为特征。

2.3.2 实例

创建Shape.cs

using System;using System.Collections.Generic;using System.Text;namespace Polymorphism{interface IShape{double CalculateArea();}// 创建圆class Circle : IShape{public double Radius { get; set; }public double CalculateArea(){return Math.PI * Radius * Radius;}}// 创建矩形类class Rectangle : IShape{public double Width { get; set; }public double Height { get; set; }public double CalculateArea(){return Width * Height;}}}

运行结果

3、Program.cs

以上三个实例的类实例化代码均在下面代码

using System;namespace Polymorphism{class Program{static void Main(string[] args){// 实例1//MyClass myClass = new MyClass();//myClass.DoSomething(7);//myClass.DoSomething("凯文");// 实例2//Dog dog = new Dog();//dog.MakeSound();//Cat cat = new Cat();//cat.MakeSound();// 实例3Circle circle = new Circle();circle.Radius = 2;double area1 = circle.CalculateArea();Console.WriteLine($"圆形面积:{area1}");Rectangle rectangle = new Rectangle();rectangle.Width = 2;rectangle.Height = 2;double area2 = rectangle.CalculateArea();Console.WriteLine($"矩形面积:{area2}");}}}