1、首先建立一个接口 interface IBankAccount
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Wrox.ProeCSharp { interface IBankAccount { void PayIn(decimal account); //方法不用实现,类继承是重写 bool WithDraw(decimal account); //方法不用实现,类继承是重写 decimal Balance { get; } //注意是属性,不是字段 } }
2、分别建立两个类,这两个类都继承于接口IBankAccount
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Wrox.ProeCSharp.VenusBank { class VenusAccount : IBankAccount { public decimal balance; public void PayIn(decimal account) { balance += account; } public bool WithDraw(decimal account) { if (balance >= account) { balance -= account; return true; } Console.WriteLine("WithDraw fail!"); return false; } public decimal Balance { get { return balance; } } public override string ToString() { return string.Format("Venus bank saver: Balance= {0,6:C}", balance); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Wrox.ProeCSharp.JupiteBank { class JupiteAccount:IBankAccount { public decimal balance; public void PayIn(decimal account) { balance += account; } public bool WithDraw(decimal account) { if (balance >= account) { balance -= account; return true; } Console.WriteLine("WithDraw fail!"); return false; } public decimal Balance { get { return balance; } } public override string ToString() { return string.Format("Gold bank saver: Balance= {0,6:C}", balance); } } }
3、Main 函数实例化类,并进行测试
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Wrox.ProeCSharp.JupiteBank; using Wrox.ProeCSharp.VenusBank; namespace Wrox.ProeCSharp { class Program { static void Main(string[] args) { VenusAccount venus = new VenusAccount(); JupiteAccount jupite = new JupiteAccount(); venus.PayIn(200); venus.WithDraw(300); Console.WriteLine(venus.ToString()); jupite.PayIn(600); jupite.WithDraw(500); jupite.WithDraw(100); Console.WriteLine(jupite.ToString()); Console.ReadLine(); } } }
4、测试结果