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 扎死你

順便復習一下抽象類和接口的一點小區別:

一個類可以去實現多個接口,表示這個類的對象可以做什么

一個類只能繼承一個抽象類,相當於派生類是一個抽象類的意思,從屬關系比較緊湊


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM