接口两种实现方式
以前在用到接口時(shí),從來(lái)沒(méi)注意到接口分為隱式實(shí)現(xiàn)與顯示實(shí)現(xiàn)。昨天在瀏覽博客時(shí)看到相關(guān)內(nèi)容,現(xiàn)在根據(jù)自己的理解記錄一下,方便日后碰到的時(shí)候溫習(xí)溫習(xí)。
?通俗的來(lái)講,“顯示接口實(shí)現(xiàn)”就是使用接口名稱作為方法名的前綴;而傳統(tǒng)的實(shí)現(xiàn)方式稱之為:“隱式接口實(shí)現(xiàn)”。費(fèi)話不說(shuō),例子如下:
? ? ?interface IAnimal { void Dog(); } class Animal:IAnimal { public void Dog() { Console.WriteLine("dog..."); } }
定義了一個(gè)IAnimal接口,一般我們都會(huì)這么調(diào)用:
//通過(guò)類調(diào)用
Animal animal = new Animal(); animal.Dog();
//或者通過(guò)接口調(diào)用
IAnimal animal = new Animal();
animal.Dog();
類和接口都能調(diào)用到,事實(shí)上這就是“隱式接口實(shí)現(xiàn)”。
那么“顯示接口實(shí)現(xiàn)”是神馬模樣呢?
interface IAnimal { void Dog(); } class Animal:IAnimal { void IAnimal.Dog() { Console.WriteLine("dog..."); } }
//只能通過(guò)接口調(diào)用
IAnimal animal = new Animal();
animal.Dog();
用類的方法去實(shí)現(xiàn)時(shí)會(huì)報(bào)錯(cuò),不允許,“顯示接口實(shí)現(xiàn)”只允許接口實(shí)現(xiàn)。如果真想用類來(lái)實(shí)現(xiàn)呢,那必須要進(jìn)行一下強(qiáng)制類型轉(zhuǎn)換。
//強(qiáng)制類型轉(zhuǎn)換后即可
Animal animal = new Animal(); (animal as IAnimal).Dog();
既然顯示接口實(shí)現(xiàn)這么不給力,為什么還要存在了,凡事存在即合理。在實(shí)際項(xiàng)目中,有時(shí)某個(gè)類往往會(huì)繼承多個(gè)接口,而接口中往往會(huì)有一些相同名稱、參數(shù)與類型的值。通過(guò)顯式接口實(shí)現(xiàn)可以為避免一些不必要的歧義(我在項(xiàng)目中碰到的不多,可能是因?yàn)轫?xiàng)目太小的原因吧)。
顯示接口實(shí)現(xiàn)與隱式接口實(shí)現(xiàn)的適應(yīng)場(chǎng)景
- 當(dāng)類實(shí)現(xiàn)一個(gè)接口時(shí),通常使用隱式接口實(shí)現(xiàn),這樣可以方便的訪問(wèn)接口方法和類自身具有的方法和屬性。
- 當(dāng)類實(shí)現(xiàn)多個(gè)接口時(shí),并且接口中包含相同的方法簽名,此時(shí)使用顯式接口實(shí)現(xiàn)。即使沒(méi)有相同的方法簽名,仍推薦使用顯式接口,因?yàn)榭梢詷?biāo)識(shí)出哪個(gè)方法屬于哪個(gè)接口。
- 隱式接口實(shí)現(xiàn),類和接口都可訪問(wèn)接口中方法。顯式接口實(shí)現(xiàn),只能通過(guò)接口訪問(wèn)。
轉(zhuǎn)載于:https://www.cnblogs.com/xietianjiao/p/5198789.html
總結(jié)
- 上一篇: 微信个性签名积极向上
- 下一篇: UITableView数据的添加、删除、