定义和实现接口
代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace ConsoleApplication1 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 IBankAccount venusAccount = new SaverAccount(); 13 ITransferBankAccount jupiterAccount = new CurrentAccount(); 14 venusAccount.PayIn(200); 15 jupiterAccount.PayIn(500); 16 Console.WriteLine(jupiterAccount.TransferTo(venusAccount, 200).ToString()); 17 Console.WriteLine(venusAccount.ToString()); 18 Console.WriteLine(jupiterAccount.ToString()); 19 Console.ReadKey(); 20 } 21 } 22 23 #region 定义和实现接口 24 public interface IBankAccount 25 { 26 void PayIn(decimal amount); 27 bool Withdraw(decimal amount); 28 decimal Balance 29 { 30 get; 31 } 32 } 33 public interface ITransferBankAccount : IBankAccount 34 { 35 bool TransferTo(IBankAccount destination, decimal amount); 36 } 37 public class CurrentAccount : ITransferBankAccount 38 { 39 private decimal balance; 40 //转账 41 public bool TransferTo(IBankAccount destination, decimal amount) 42 { 43 bool result = false; 44 result = Withdraw(amount); 45 if (result) 46 { 47 destination.PayIn(amount); 48 } 49 return result; 50 } 51 //进账 52 public void PayIn(decimal amount) 53 { 54 balance += amount; 55 } 56 //出账 57 public bool Withdraw(decimal amount) 58 { 59 if (balance >= amount) 60 { 61 balance -= amount; 62 return true; 63 } 64 Console.WriteLine("Withdrawal attempt failed."); 65 return false; 66 } 67 68 public decimal Balance 69 { 70 get { return balance; } 71 } 72 public override string ToString() 73 { 74 return string.Format("Jupiter Blank Current Account:Balance={0,6:C}", balance); 75 } 76 } 77 public class SaverAccount : IBankAccount 78 { 79 private decimal balance; 80 public void PayIn(decimal amount) 81 { 82 balance += amount; 83 } 84 85 public bool Withdraw(decimal amount) 86 { 87 if (balance >= amount) 88 { 89 balance -= amount; 90 return true; 91 } 92 Console.WriteLine("Withdrawal attempt failed."); 93 return false; 94 } 95 96 public decimal Balance 97 { 98 get { return balance; } 99 } 100 public override string ToString() 101 { 102 return string.Format("Venus bank Saver:Balance={0,6:C}", balance); 103 } 104 } 105 #endregion 106 107 }
结果:
Android 成长之路

浙公网安备 33010602011771号