C#接口的實(shí)現(xiàn)實(shí)例淺析
C#接口的實(shí)現(xiàn)是如何的呢?盡管接口只負(fù)責(zé)定義,不負(fù)責(zé)實(shí)現(xiàn),具體的實(shí)現(xiàn)是交給他的子類去完成的。 OK,現(xiàn)在我們實(shí)例的演示中來看看具體的C#接口的實(shí)現(xiàn)。
就拿我的趣味編程中的玩剪刀石頭布的案例來說吧,爺爺和奶奶從小就教授小孫子各中東西,其中玩趣味游戲就他們常有的事,可小孫子還小不知道變換,每次都出剪刀,這樣能贏他爺爺嗎?有了這個(gè)分析,我們可以怎么做呢?上面定義了接口,我們是不是直接去實(shí)現(xiàn)這個(gè)接口便OK了。爺爺和小孫子玩游戲,那么就定義兩個(gè)類去繼承IPlayer接口。代碼如下:
- /**////
- /// 出手動(dòng)作狀態(tài)
- ///
- public class Options
- {
- public static readonly string JIANDAO = "剪刀";
- public static readonly string SHITOU = "石頭";
- public static readonly string BU = "布";
- }
游戲里只會(huì)出現(xiàn)這三種動(dòng)作狀態(tài),所以我們可以進(jìn)行封裝,這里是通過類封裝的,當(dāng)然我們也可以通過別的相關(guān)技術(shù)來封裝,比如在本系列第二篇文章《C#編程利器之二:結(jié)構(gòu)與枚舉(Structure and enumeration)》 里介紹的結(jié)構(gòu)與枚舉,本例中所出現(xiàn)的這三中不變的狀態(tài)完全可以使用結(jié)構(gòu)或枚舉來封裝,詳細(xì)請閱讀上篇文章。下面是定義爺爺(Grandpa)類和孫子(Grandson)類去實(shí)現(xiàn)接口(IPlayer)了。代碼如下:
- /**////
- /// 爺爺--玩家之一
- ///
- public class Grandpa:IPlayer
- {
- public string GetName()
- {
- return "爺爺";
- }
- public string Show()
- {
- Random random = new Random();
- int i = (int)(random.Next() * 1000) % 3;
- switch (i)
- {
- case 0: return Options.JIANDAO;
- case 1: return Options.SHITOU;
- default: return Options.BU;
- }
- }
- }
- /**////
- /// 孫子--玩家之一
- ///
- public class Grandson:IPlayer
- {
- public string GetName()
- {
- return "孫子";
- }
- public string Show()
- {
- return Options.JIANDAO;
- }
- }
如上,我們的GrandPa和GrandSon就實(shí)現(xiàn)了接口IPlayer,如下圖示:
C#接口的實(shí)現(xiàn)實(shí)例的介紹就向你講述到這里,希望對你了解和學(xué)習(xí)C#接口的實(shí)現(xiàn)有所幫助。
【編輯推薦】