接口定義了所有類繼承接口時(shí)應(yīng)遵循的語法合同。接口定義了語法合同 "是什么" 部分,派生類定義了語法合同 "怎么做" 部分。
接口定義了屬性、方法和事件,這些都是接口的成員。接口只包含了成員的聲明。成員的定義是派生類的責(zé)任。接口提供了派生類應(yīng)遵循的標(biāo)準(zhǔn)結(jié)構(gòu)。
抽象類在某種程度上與接口類似,但是,它們大多只是用在當(dāng)只有少數(shù)方法由基類聲明由派生類實(shí)現(xiàn)時(shí)。
聲明接口
接口使用 interface 關(guān)鍵字聲明,它與類的聲明類似。接口聲明默認(rèn)是 public 的。下面是一個(gè)接口聲明的實(shí)例:
public interface ITransactions { // 接口成員 void showTransaction(); double getAmount(); }
實(shí)例
下面的實(shí)例演示了上面接口的實(shí)現(xiàn):
using System.Collections.Generic; using System.Linq; using System.Text; namespace InterfaceApplication { public interface ITransactions { // 接口成員 void showTransaction(); double getAmount(); } public class Transaction : ITransactions { private string tCode; private string date; private double amount; public Transaction() { tCode = " "; date = " "; amount = 0.0; } public Transaction(string c, string d, double a) { tCode = c; date = d; amount = a; } public double getAmount() { return amount; } public void showTransaction() { Console.WriteLine("Transaction: {0}", tCode); Console.WriteLine("Date: {0}", date); Console.WriteLine("Amount: {0}", getAmount()); } } class Tester { static void Main(string[] args) { Transaction t1 = new Transaction("001", "8/10/2012", 78900.00); Transaction t2 = new Transaction("002", "9/10/2012", 451900.00); t1.showTransaction(); t2.showTransaction(); Console.ReadKey(); } } }
當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:
Transaction: 001 Date: 8/10/2012 Amount: 78900 Transaction: 002 Date: 9/10/2012 Amount: 451900