文章目录
- 题目
- 步骤
- 仓库
- 总结
一、题目
程序设计题:请使用委托实现信用卡用户定时还款功能
本题的应用场景解释:用户有一张信用卡,信用卡有一个总额度;每个月会有信用卡账单显示月消费总额,月消费总额是小于信用卡总额度的;用户有若干储蓄卡,可选择某张储蓄卡进行还款;还款是指从储蓄卡中划走信用卡的月消费总额到信用卡;如果储蓄卡余额不足则还款动作不成功。
要求如下:①必须使用委托②事件的触发方式是每个月的到期还款日;
二、使用步骤
1.引入库
代码如下(示例):
using System;
using System.Collections.Generic;
namespace card_work
{
class depositCard
{
//储蓄名
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.ReadKey();
}
//无需还款
public void norepayM()
{
Console.WriteLine("用户{ 0}当前金额{ 1}", this.name, this.DC.getDepositMoney());
Console.WriteLine("用户未到还款日期,无需还款", this.name);
Console.ReadKey ();
}
}
//扣款委托类
class repayDelegate
{
//扣款委托
public delegate void repayMoney();
//扣款事件
public event repayMoney DoRepay;
//事件执行
public void NotifyRepay()
{
if (DoRepay != null)
{
Console.WriteLine("触发事件:");
DoRepay();
}
}
}
class Program
{
static void Main(string[] args)
{
depositCard D1 = new depositCard("张三", 10000);
depositCard D2 = new depositCard("李四", 10000);
depositCard D3 = new depositCard("王五", 10000);
creditCard C1 = new creditCard("张三", -5000, 5, D1);
creditCard C2 = new creditCard("李四", -3000, 31, D2);
creditCard C3 = new creditCard("王五", -1000, 5, 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();
}
}
}
结果截图
2.仓库地址
陈元鹏/scghttps://gitee.com/Chen__address/scg
。
总结
了接到了委托和事件