C#“委托”和“事件”模拟信用卡还款
前言
- “委托”,“事件”是C#编程语言的高级特性之一。
- “委托”类似于C语言中的函数指针,使相同类型,相同形参的函数能被灵活的切换和使用。
- 其实“事件”的类型就是“委托”,被称为回调方法。
- gitee网址:https://gitee.com/kittysmith5/csharp-learning-record/blob/master/cs-code/creditcard/ConsoleApp/Program.cs
核心代码
委托和事件声明类
1 class CreditCardDelegete 2 { 3 public delegate void card(User uesr); 4 public event card DeMoney;//定期扣款事件绑定委托 5 6 //判断事件是否启用 7 public void DeMoneyTest(User user) 8 { 9 if (DeMoney != null) 10 { 11 DeMoney(user); 12 } 13 else 14 { 15 Console.WriteLine("还款日未到"); 16 } 17 } 18 }
用户字段类
class User { private int balance; private int debt; private string name; private int day; public User(int balance, int debt, string name, int date) { this.balance = balance; this.debt = debt; this.name = name; this.day = date; } //属性,用匿名函数赋值、取值 public int Balance { get => balance; set => balance = value; } public string Name { get => name; set => name = value; } public int Debt { get => debt; set => debt = value; } public int Date { get => day; set => day = value; } }
银行还款系统类
class Bank { public void DeMoneying(User user) { Console.WriteLine("{0},您的信用卡余额为{1}元,本次还款{2}元,信用卡目前余额为{3}元!", user.Name, user.Balance, user.Debt, (user.Balance - user.Debt)); Console.WriteLine(); } }
main方法入口
1 static void Main(string[] agrs) 2 { 3 CreditCardDelegete d1 = new CreditCardDelegete(); 4 5 User user = new User(521, 520, "马化腾", 8000); 6 Bank bank = new Bank(); 7 8 d1.DeMoney += bank.DeMoneying;//银行扣款函数订阅扣款事件 9 10 11 for (int i = 0; i <= 10000; i++) 12 { 13 if (i == user.Date) 14 d1.DeMoneyTest(user); 15 } 16 }
输出结果