本题的应用场景解释:用户有一张信用卡,信用卡有一个总额度;每个月会有信用卡账单显示月消费总额,月消费总额是小于信用卡总额度的;用户有若干储蓄卡,可选择某张储蓄卡进行还款;还款是指从储蓄卡中划走信用卡的月消费总额到信用卡;如果储蓄卡余额不足则还款动作不成功。
要求如下:
①必须使用委托
②事件的触发方式是每个月的到期还款日;
实验过程:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp8
{
public class Card
{
private string name;//储蓄卡名
private int amount;//金额
public Card(string name, int amount)
{
this.name = name;
this.amount = amount;
}
public int GetMoney()
{
return this.amount;
}
public void SetMoney(int r)
{
this.amount = r;
}
}
public class creditCard
{
public string name;
private int balance;//信用卡余额
public int Date;//扣款日期
private Card DC;//绑定储蓄卡对象
public creditCard(string name, int balance, int Date, Card DC)
{
this.name = name;
this.balance = balance;
this.Date = Date;
this.DC = DC;
}
public void Repayment() //还款
{
Console.WriteLine("用户{0}当前金额{1}", this.name, this.DC.GetMoney());
DC.SetMoney(this.DC.GetMoney() + balance);
Console.WriteLine("用户已还款");
Console.WriteLine("还款金额:"+ Math.Abs(this.balance));
Console.WriteLine("余下金额为"+ DC.GetMoney());
}
public void NoRepayment()
{
Console.WriteLine("未到还款日期,用户无需还款");
Console.WriteLine("余下金额为"+ DC.GetMoney());
}
}
class Delegate//还款委托类
{
public delegate void repayMoney();//还款委托
public event repayMoney DoRepay;//还款事件
public void NotifyRepay()//事件执行
{
if (DoRepay != null)
{
Console.WriteLine("触发事件:");
DoRepay();
}
}
}
class Program
{
static void Main(string[] args)
{
Card D1 = new Card("Anna", 10000);
Card D2 = new Card("Bob", 20000);
Card D3 = new Card("Jack", 15000);
creditCard C1 = new creditCard("Anna", -1000, 1, D1);
creditCard C2 = new creditCard("Bob", -5000, 2, D2);
creditCard C3 = new creditCard("Jack", -1500, 5, D3);
ArrayList Cards = new ArrayList();
Cards.Add(C1);
Cards.Add(C2);
Cards.Add(C3);
//创建委托对象
Delegate rD = new Delegate();
foreach (creditCard C in Cards)
{
//判断是否到了该还款的日期
if (C.Date == int.Parse(DateTime.Now.ToString("yyyy-MM-dd").Split('-')[2]))
{
//事件添加
rD.DoRepay += new Delegate.repayMoney(C.Repayment);
}
else
{
rD.DoRepay += new Delegate.repayMoney(C.NoRepayment);
}
}
//事件执行
rD.NotifyRepay();
Console.ReadLine();
}
}
}