using System; using System.Collections.Generic; using System.Text; using Wrox.ProCSharp.VenusBank; namespace Wrox.ProCSharp ... { public interface IBankAccount ...{ void PayIn(decimal amount); //存款的方法 bool Withdraw(decimal amount); //判断是否余款不足 decimal Balance //返回余款的属性 ...{ get; } } public interface ITransferBankAccount : IBankAccount ...{ bool TransferTo(IBankAccount destination, decimal amount); } public class XufangweiAccount : ITransferBankAccount ...{ //实现接口 private decimal balance; public void PayIn(decimal amount) ...{ balance += amount; } public bool Withdraw(decimal amount) ...{ if (balance >= amount) ...{ balance -= amount; return true; } Console.WriteLine("转帐失败"); return false; } public decimal Balance ...{ get ...{ return balance; } } public bool TransferTo(IBankAccount destination, decimal amount) ...{ bool result; if ((result = Withdraw(amount))==true) destination.PayIn(amount); return result; } public override string ToString() ...{ return String.Format("xfw Bank Current Account: Balance = {0,6:C}", balance); } } class MainEntryPoint ...{ static void Main() ...{ IBankAccount cyyAccount = new ChenyeyeAccount(); //以上已经详细说明表示他们可以指向实现这些接口的任何方法 ITransferBankAccount xfwAccount = new XufangweiAccount(); cyyAccount.PayIn(200); xfwAccount.PayIn(500); xfwAccount.TransferTo(cyyAccount, 100); Console.WriteLine(cyyAccount.ToString()); Console.WriteLine(xfwAccount.ToString()); } } } namespace Wrox.ProCSharp.VenusBank ... { public class ChenyeyeAccount : IBankAccount ...{ private decimal balance; public void PayIn(decimal amount) ...{ balance += amount; } public bool Withdraw(decimal amount) ...{ if (balance >= amount) ...{ balance -= amount; return true; } Console.WriteLine("转帐失败."); return false; } public decimal Balance ...{ get ...{ return balance; } } public override string ToString() ...{ return String.Format("cyy Bank Saver: Balance = {0,6:C}", balance); } }} /**/ /*总结: * 这也是一个银行转帐的东东,不同的是转入转出比先前多了一个帐户信息,刚才的例子只是帐户之间钱的增加和减少, * 为了增加转帐户信息,这里派生了一个接口 * public interface ITransferBankAccount : IBankAccount { bool TransferTo(IBankAccount destination, decimal amount); } * 该接口的功能与IBankAccount相同,只是又定义了一个方法,把资金直接转到另一个账户上。 * * 注意::: * ITransferBankAccount派生于IBankAccount,所以拥有IBankAccount的所有成员和它自己的成员。 * 这表示执行(派生于)ITransferBankAccount的任何类都必须执行IBankAccount的所有方法和在ITransferBankAccount * 中定义的新方法TransferTo()。没有执行所有这些方法就会出现编译错误:如:“不会实现接口成员” */