C#实现多态的几种

一:多态的理解

父类类型和子类类型可以使用同一个(方法名的)方法而输出不同的结果;例如父类可以使用虚函数,子类可以选择重写虚函数(或者不重写),子类对象调用方法的时候可以选择使用父类中的虚方法或者子类中重写的方法;

下面是微软给出的官方文档:https://docs.microsoft.com/zh-cn/dotnet/csharp/fundamentals/object-oriented/polymorphism

 

二:多态的实现.

1、里氏转换:

 1    class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             Animal animal1 = new Animal();
 6             Animal animal2 = new Dog();
 7             animal1.Shou();
 8             animal2.Shou();
 9             Console.ReadKey();
10         }
11     }
12 
13     public class Animal
14     {
15         public virtual void Shou()
16         {
17             Console.WriteLine("动物在发声");
18         }
19     }
20     public class Dog:Animal
21     {
22         public override void Shou()
23         {
24             Console.WriteLine("小狗汪汪汪");
25         }
26     }

/* Output:

动物在发声
小狗汪汪汪

*/

 

2、接口实现:

 1     public interface ICar
 2     {
 3         void Run();
 4     }
 5 
 6     public class Suv : ICar
 7     {
 8         public void Run()
 9         {
10             Console.WriteLine("SUV汽车跑");
11         }
12     }
13 
14    class Program
15     {
16         static void Main(string[] args)
17         {
18             ICar car = new Suv();
19             car.Run();
20         }
21     }

    /* output: SUV汽车跑
    */

 

posted @ 2022-05-08 21:18  yangbe1  阅读(488)  评论(0编辑  收藏  举报