C#接口实现多态

我比较喜欢对感兴趣的理论进行反复的理解甚至理解背诵下来,接下来再复习一下什么叫多态(哈哈哈)

多态:在同一粒度视图下对相同类型的事物不做区别的统一操作

接下来看一下接口和引擎类是如何实现多态的:

一、

1、创建了一个接口类:IWeapon

1 public interface IWeapon
2     {
3         void Fire();
4     }

2、声明几个类去实现这个接口(展示描述的词语是我老师的佳作,我可是软妹子(哈哈哈))

 1  public class Gun : IWeapon
 2     {
 3         public void Fire()
 4         {
 5             Console.WriteLine("pa peng pa peng");
 6         }
 7     }
 8 
 9     public class Sword : IWeapon
10     {
11         public void Fire()
12         {
13             Console.WriteLine("七剑下天山");
14         }
15 
16     }
17 
18     public class Tank : IWeapon
19     {
20         public void Fire()
21         {
22             Console.WriteLine("压死你");
23         }
24     }
25 
26     public class Xiaomugun : IWeapon
27     {
28         public void Fire()
29         {
30             Console.WriteLine("扎死你");
31         }
32     }

3、创建一个引擎类:Engine(以接口为参数)

1 public static void Play(IWeapon w)
2         {
3             w.Fire();
4         }

4、在程序入口处调用引擎类,实现多态

1 InterfaceDemo.Engine.Play(new InterfaceDemo.Gun());
2 InterfaceDemo.Engine.Play(new InterfaceDemo.Sword());
3 InterfaceDemo.Engine.Play(new InterfaceDemo.Tank());
4 InterfaceDemo.Engine.Play(new InterfaceDemo.Xiaomugun());

上面调用的结果是:

1 pa peng pa peng
2 七剑下天山
3 压死你
4 扎死你

顺便复习一下抽象类和接口的一点小区别:

一个类可以去实现多个接口,表示这个类的对象可以做什么

扫描二维码关注公众号,回复: 6074709 查看本文章

一个类只能继承一个抽象类,相当于派生类是一个抽象类的意思,从属关系比较紧凑

猜你喜欢

转载自www.cnblogs.com/fllowerqq/p/10797522.html
今日推荐