聊一聊C#接口問題 新手速來圍觀
這段時間的項目有用到接口,開始不是特別理解接口,只是單單知道接口定義非常簡單,甚至覺得這個接口只是多此一舉(個人開發(fā)的時候)。現在開始團隊開發(fā),才發(fā)現接口原來是這么的重要和便捷!
接下來就來談談我這段時間對接口使用的粗淺見解,說的對希望大家贊,說的有誤的地方希望大家多多包涵建議!
READY GO!
接口的定義就不多說了,它有一個很重要的知識點,就是所有繼承這個接口類的都必須實現接口中的定義,說到這個必須,在團隊開發(fā)中,只要我們商定好了接口,那我們的代碼是不是就統(tǒng)一了?。。?nbsp;
這是我覺得接口重要的第一點:它便于我們統(tǒng)一項目的規(guī)定,便于團隊代碼的管理!
再來用一個例子說明:
A公司決定開發(fā)一套動物系統(tǒng),其中包含很多的動物,公司決定要實現每個動物的喊叫行為……
說到這里,我們一般就是各個程序員拿到自己要實現的動物類之后就開始大刀闊斧的開干了!?。?br />
X程序員實現狗這個類,他寫一個叫喊方法void Han(){……}
Y程序員實現貓這個類,他寫一個叫喊方法void Shout(){……}
M程序員實現豬這個類,他寫一個叫喊方法 void Shout(string content){……}
………………
好了,現在都完成了各自需要完成的動物,隔壁老王開始來實現百獸齊鳴!?。?!&¥%¥*%¥¥%¥一頓粗口爆出!這要怎么寫?一個個去調用???
來看看,X程序員英語不太好,也沒有過多的去管,只是寫出動物叫喊的方法,Y程序員和M程序員寫的叫喊方法名稱是一樣,但M程序員中還要傳遞動物叫喊的內容?。。。?!
隔壁老王現在要讓所有動物都叫一遍就得一個動物一個動物的去調用方法……
OK,接下來開會商量,隔壁老王定義一個動物接口,所有的動物類都得繼承這個接口,這個接口只定義一個void Shout(); (就不過多的寫東西啦,偷偷懶)
X,Y,M程序員繼承后,X,M立馬就發(fā)現有問題,然后開始改了自己手中的類
這時老王就開始來百獸齊鳴啦!哈哈哈哈哈
接下來貼出代碼大家看
接口
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InterfaceProject { /// <summary> /// 動物接口 /// </summary> interface IAnimal { /// <summary> /// 動物叫喊 /// </summary> void Shout(); } }
狗
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InterfaceProject { /// <summary> /// 狗 /// </summary> public class Dog:IAnimal { public void Shout() { Console.WriteLine("汪汪汪"); } } }
貓
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InterfaceProject { /// <summary> /// 貓 /// </summary> public class Cat:IAnimal { public void Shout() { Console.WriteLine("喵喵喵"); } } }
豬
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InterfaceProject { /// <summary> /// 豬 /// </summary> public class Pig:IAnimal { public void Shout() { Console.WriteLine("豬怎么叫來著??豬叫"); } } }
隔壁老王來實現百獸齊鳴(打倒老王這種人物的存在)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InterfaceProject { class Program { static void Main(string[] args) { //百獸齊鳴(這里可以使用反射來初始化所有繼承IAnimal的所有動物,我就不寫這個了,主要看接口) List<IAnimal> animals = new List<IAnimal>(); IAnimal dog = new Dog(); animals.Add(dog); IAnimal cat = new Cat(); animals.Add(cat); IAnimal pig = new Pig(); animals.Add(pig); //所有動物都叫一遍 for (int i = 0; i < animals.Count; i++) { animals[i].Shout(); } } } }
我對這個接口的粗略見解就說完啦!接口這個東西雖然用起來很簡單,但我們還是要理解這個接口的作用,希望我的這篇文章能夠讓更多像我一樣的新手向接口這個東西邁出第一步。
相關文章
同時兼容JS和C#的RSA加密解密算法詳解(對web提交的數據加密傳輸)
這篇文章主要給大家介紹了關于同時兼容JS和C#的RSA加密解密算法,通過該算法可以對web提交的數據進行加密傳輸,文中通過圖文及示例代碼介紹的非常詳細,需要的朋友們可以參考借鑒,下面來一起看看吧。2017-07-07c# 使用谷歌身份驗證GoogleAuthenticator的示例
這篇文章主要介紹了c# 使用谷歌身份驗證GoogleAuthenticator的示例,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2021-01-01