C#interface定義及使用淺析
C# interface定義及使用的問(wèn)題:接口定義以大寫字母I開頭。方法只定義其名稱,在C#中,方法默認(rèn)是公有方法;用public修飾方法是不允許的,否則會(huì)出現(xiàn)編譯錯(cuò)誤;接口可以從別的接口繼承,如果是繼承多個(gè)接口,則父接口列表用逗號(hào)間隔。
C# interface可以通過(guò)類來(lái)實(shí)現(xiàn),當(dāng)類的基列表同時(shí)包含基類和接口時(shí),列表中首先出現(xiàn)的是基類;類必須要實(shí)現(xiàn)其抽象方法;
C# interface定義及使用實(shí)例:
- using System;
- namespace Dage.Interface
- {
- //打印機(jī)接口
- public interface IPrint
- {
- string returnPrintName();
- }
- }
- //C# interface應(yīng)用實(shí)現(xiàn)
- using System;
- using Dage.Interface;
- namespace Dage.Print
- {
- //HP牌打印機(jī)類
- public class HP: IPrint
- {
- public string returnPrintName()
- {
- return "這是HP牌打印機(jī)";
- }
- }
- }
- //C# interface應(yīng)用實(shí)現(xiàn)
- using System;
- namespace Dage.Print
- {
- //Eps牌打印機(jī)類
- public class Eps: IPrint
- {
- public string returnPrintName()
- {
- return "這是Eps牌打印機(jī)";
- }
- }
- }
- //C# interface應(yīng)用實(shí)現(xiàn)
- using System;
- using Dage.Interface;
- namespace Dage
- {
- //打印類
- public class Printer
- {
- public Printer()
- {}
- public string PrintName(IPrint iPrint)
- {
- return iPrint.returnPrintName();
- }
- }
- }
- //C# interface應(yīng)用實(shí)現(xiàn)
- --WinFrom中調(diào)用代碼:
- private void button1_Click(object sender, System.EventArgs e)
- {
- Printer p= new Printer();
- switch (this.comboBox1.Text)
- {
- case "HP":
- MessageBox.Show(p.PrintName(new HP()));
- break;
- case "Eps":
- MessageBox.Show(p.PrintName(new Eps()));
- break;
- default:
- MessageBox.Show("沒有發(fā)現(xiàn)這個(gè)品牌!");
- break;
- }
- }
C# interface定義與使用的基本內(nèi)容和相關(guān)的理解就向你介紹到這里,希望對(duì)你了解和學(xué)習(xí)C# interface的定義與使用有所幫助。
【編輯推薦】