C#-委托与事件
委托实现信用卡用户定时还款功能
问题的核心
通过使用C#的委托与事件,实现信用卡绑定银行卡然后定时帮用户进行信用卡从储蓄卡中扣款的还款功能。
核心代码
1.定义信用卡类和储蓄卡类
class DepCard //储蓄卡{public string cardName;public int cardMoney;public DepCard(string name, int money){this.cardName = name;this.cardMoney = money;}public void SetMoney(int m){this.cardMoney = m;}}class CredCard //信用卡类{public string cardName;public int cardMoney;public int dueDay;public DepCard card;public CredCard(string name, int money, int day, DepCard card){this.cardName = name;this.cardMoney = money;this.dueDay = day;this.card = card;}public void ReMoney() //需要还款{Console.WriteLine("用户:{0}", this.cardName);Console.WriteLine("当前金额为:{0}",this.card.cardMoney);this.card.cardMoney += cardMoney;Console.WriteLine("已到还款日期,还款金额为:{0}", -this.cardMoney);Console.WriteLine("剩下的金额为:{0}", card.cardMoney);Console.WriteLine();}public void noReMoney() //无需还款{Console.WriteLine("用户:{0}", this.cardName);Console.WriteLine("当前金额为:{0}", this.card.cardMoney);Console.WriteLine("未到还款日期,无需还款!");Console.WriteLine("剩下的金额为:{0}", card.cardMoney);Console.WriteLine();}}
2.定义委托事件`
class Delegate{//定义委托和事件public delegate void reMoney();public event reMoney NotifyRepay;public void Notify(){if (NotifyRepay != null){Console.WriteLine("触发事件:");NotifyRepay();}}}
3.判断函数
class TestEvents{static void Test(CredCard card, Delegate De){//判断是否到还款日期然后订阅事件if (card.dueDay == int.Parse(DateTime.Now.Day.ToString())){De.NotifyRepay += new Delegate.reMoney(card.ReMoney);}else{De.NotifyRepay += new Delegate.reMoney(card.noReMoney);}}
4.主程序
static void Main(string[] args){//建立储蓄卡和信用卡的对象并初始化DepCard Dcard1 = new DepCard("小李", 5000);CredCard c1 = new CredCard("小李",-1000, 8, Dcard1);DepCard Dcard2 = new DepCard("小周", 6000);CredCard c2 = new CredCard("小周", -3000, 31, Dcard2);//创建委托的对象Delegate De = new Delegate();//判断并调用委托事件Test(c1,De); Test(c2,De);De.Notify();Console.ReadLine();}
结果截图

实验小结
委托是一种可以指向方法的引用,类似于C++中的函数指针,通过对于方法特征和返回值类型的声明,封装了具有相同特征和返回类型的方法。程序员可以将方法引用封装在委托对象内,然后可以将该委托对象传递给可调用所引用方法的代码,而不必在编译时知道将调用哪个方法,使编写程序更加简单。
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
