C#作业二用委托和事件实现信用卡还款功能:
信用卡和存储卡保存着用的金额,通过还款类判断今日是否需要还款,以及是否可以还款成功,最后完成还款这个事件。
定义信用卡类、存储卡类、还款类`
{
private string name;
private int depositMoney;
public depositCard(string name, int money)
{
this.name = name;
this.depositMoney = money;
}
public int getDepositMoney()
{
return this.depositMoney;
}
public void setDepositMoney(int r)
{
this.depositMoney = r;
}
}
//信用卡类
class creditCard
{
public string name;
public int creditMoney;
public int dueDay;
public depositCard DC;
public creditCard(string name, int CM, int DD, depositCard DC)
{
this.name = name;
this.creditMoney = CM;
this.dueDay = DD;
this.DC = DC;
}
//还款
public void repayM()
{
Console.WriteLine("用户{0}当前金额{1}", this.name, this.DC.getDepositMoney());
DC.setDepositMoney(this.DC.getDepositMoney() + creditMoney);
Console.WriteLine("用户已还款");
Console.WriteLine("还款金额:{0}", Math.Abs(this.creditMoney));
Console.WriteLine("余下金额为{0}", DC.getDepositMoney());
Console.WriteLine();
}
//无需还款
public void norepayM()
{
Console.WriteLine("用户{0}当前金额{1}", this.name, this.DC.getDepositMoney());
Console.WriteLine("用户未到还款日期,无需还款", this.name);
Console.WriteLine();
}
}`
主函数
depositCard D1 = new depositCard("张三", 10000);
depositCard D2 = new depositCard("李四", 10000);
depositCard D3 = new depositCard("王五", 10000);
creditCard C1 = new creditCard("张三", -8000, 31, D1);
creditCard C2 = new creditCard("李四", -3000, 7, D2);
creditCard C3 = new creditCard("王五", -7000, 7, D3);
List<creditCard> cCards = new List<creditCard>();
cCards.Add(C1);
cCards.Add(C2);
cCards.Add(C3);
//创建委托对象
repayDelegate rD = new repayDelegate();
foreach (creditCard C in cCards)
{
//判断是否到了该还款的日期
if (C.dueDay == int.Parse(DateTime.Now.ToString("yyyy-MM-dd").Split('-')[2]))
{
rD.DoRepay += new repayDelegate.repayMoney(C.repayM);
}
else
{
rD.DoRepay += new repayDelegate.repayMoney(C.norepayM);
}
}
rD.NotifyRepay();
运行结果
gitee:添加链接描述