已有两个接口,IBankAccount接口代表一个银行账户能提供的操作,包括存入、支付、查询余额。ITransferBankAccount接口继承IBankAccount接口,并提供转账功能。 public interface IBankAccount { void PayIn(decimal amount); bool Withdraw(decimal amount); decimal Balance { get; } } public interface ITransferBankAccount : IBankAccount { bool TransferTo(IBankAccount destination, decimal amount); } 要求写三个类,按以下方式构建继承体系,并重载ToString方法,输出账户主要信息。 1)类SaverAccount继承接口IBankAccount。当支付金额超出余额时应打印出错信息。 2)类TransferBankAccount继承类SaverAccount和接口ITransferBankAccount。 3)类CreditAccount继承IBankAccount,并添加Limit属性,代表透支额度。在支付时,若透支应打印提示信息;若超出透支额度,支付不成功,应打印出错信息。 运行以下测试程序,将输出结果粘贴 IBankAccount sa = new SaverAccount { Balance = 500 }; sa.PayIn(100); sa.Withdraw(550); WriteLine(sa); WriteLine(); ITransferBankAccount tba = new TransferBankAccount { Balance = 700 }; tba.TransferTo(sa, 750); tba.TransferTo(sa, 200); WriteLine(tba); WriteLine(); IBankAccount ca = new CreditAccount { Balance = 100, Limit = 500 }; ca.Withdraw(300); ca.Withdraw(400); WriteLine(ca); 解答: using static System.Console; namespace ConsoleApp5 { 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 SaverAccount : IBankAccount { public void PayIn(decimal amount) => Balance += amount; public virtual bool Withdraw(decimal amount) { if (Balance >= amount) { Balance -= amount; return true; } WriteLine("支付失败!"); return false; } public decimal Balance { get; set; } public override string ToString() => $"存款账户:余额 = {Balance,6:C}"; } public class TransferBankAccount : SaverAccount, ITransferBankAccount { public bool TransferTo(IBankAccount destination, decimal amount) { bool result = Withdraw(amount); if (result) { destination.PayIn(amount); WriteLine("转账成功!"); } return result; } public override string ToString() => $"转账账户:余额 = {Balance,6:C}"; } public class CreditAccount : SaverAccount { public decimal Limit { get; set; } public override bool Withdraw(decimal amount) { if (Balance >= amount) { Balance -= amount; return true; } else if (Balance + Limit > amount) { Balance -= amount; WriteLine("支付成功,已透支!"); return true; } else { WriteLine("超出限额,支付失败!"); return false; } } public override string ToString() => $"信用卡账户:余额 = {Balance,6:C}, 透支额度 = {Limit,6:C}"; } class Ex4 : Object { public static void Main() { IBankAccount sa = new SaverAccount { Balance = 500 }; sa.PayIn(100); sa.Withdraw(550); WriteLine(sa); WriteLine(); ITransferBankAccount tba = new TransferBankAccount { Balance = 700 }; tba.TransferTo(sa, 750); tba.TransferTo(sa, 200); WriteLine(tba); WriteLine(); IBankAccount ca = new CreditAccount { Balance = 100, Limit = 500 }; ca.Withdraw(300); ca.Withdraw(400); WriteLine(ca); } } }