之前一直不理解接口這一概念,今天無意中翻書,網上查資料悟道其中的道理,現在工作沒有用到interface這一塊,怕以后會遇到忘記實現的方法便記錄下來,哪里寫的不對希望讀者指出,話不多說,接下來看我對接口的理解。
1.接口說明:
接口為不同應用的實現提供了一中規范和約束,只要每個應用都遵守這種規范和約束,整個系統就可以得到有效的組織,從而為應用系統的低代價開發提供有效的途徑。
接口用於描述一組類的公共方法/公共屬性. 它不實現任何的方法或屬性,只是告訴繼承它的類《至少》要實現哪些功能,繼承它的類可以增加自己的方法。
2.接口聲明:
interface ISample { void f(int x); //方法 int att { get; set; } //屬性(可讀,可寫) event EventHandler OnDraw; //事件 string this[int index] { get; set; } //索引器 }
3.接口使用注意事項:
1.接口可以繼承。 2.類要繼承接口的所有東西 3.接口不能繼承類 4.一個類可以繼承多個接口 5.接口的修飾符可以是 new、public、protected、internal、private 6.接口成員前面不允許有修飾符,都默認為公有成員(public) 7.接口成員可以分為4類:方法、屬性、事件、索引器,而不能包含成員變量
4.實例
public class Program { static void Main(string[] args) { Dog dog = new Dog(); dog.Cay(); Cat cat = new Cat(); cat.Cay(); Pig pig = new Pig(); pig.Cay(); Console.Read(); } } class Dog : Animal //定義狗的類 { public void Cay() //輸出狗叫聲的方法 { Console.WriteLine("汪汪汪"); } } class Cat : Animal //定義貓的類 { public void Cay() //輸出貓叫聲的方法 { Console.WriteLine("喵喵喵"); } } class Pig : Animal //定義豬的類 { public void Cay() //輸出豬叫聲的方法 { Console.WriteLine("哼哼哼"); } } interface Animal //動物接口 { void Cay(); //叫聲的方式 }
輸出的結果:
這樣一看,如果想要調用Cay()方法,在Dog,Cat,Pig中直接定義不就好了,何必多次一舉?
那么我們修改一下代碼,再定義一個類Class,這個Class作為實現接口傳入,這個類不需要繼承於接口Animal:
public class Program { static void Main(string[] args) { Class c = new Class(); Animal animal; animal = new Dog(); c.WriteCay(animal); animal = new Cat(); c.WriteCay(animal); animal = new Pig(); c.WriteCay(animal); Console.Read(); } } class Dog : Animal //定義狗的類 { public void Cay() //輸出狗叫聲的方法 { Console.WriteLine("汪汪汪"); } } class Cat : Animal //定義貓的類 { public void Cay() //輸出貓叫聲的方法 { Console.WriteLine("喵喵喵"); } } class Pig : Animal //定義豬的類 { public void Cay() //輸出豬叫聲的方法 { Console.WriteLine("哼哼哼"); } } class Class { public void WriteCay(Animal animal) { animal.Cay(); Console.WriteLine("--------------------------"); } } interface Animal //動物接口 { void Cay(); //叫聲的方式 }
此時的函數的結果是:
如果再來一個Monkey,Cattle,Sheep這樣的類添加進來,也只需要把他們的相關類加進來,然后在Main()中稍作修改就好,擴充性特別好。