#1.发布器,在其中定义委托与事件,事件与委托绑定,委托的参数为一个用户对象,用于对不同用户触发不同的事件。
using System;
namespace ConsoleApp3
{
class 储蓄
{
int 余额 = 9999;
信用 x;
public 储蓄(信用 x)
{
this.x = x;
}
public void 扣款操作()
{
if (x.检验是否还款() == 1)
{
余额 = 余额 - x.获取待还款金额();
Console.WriteLine("还款成功,你的余额为:{0}", 余额);
}
else
{
Console.WriteLine("尚不需要还款,你的余额为:{0}", 余额);
}
}
}
#2.银行类,定义
class 信用
{
int 还款日 = 28;
int 待还款金额;
int 还款的日期;
public 信用(int 还款金额, int 还款日期)
{
this.待还款金额 = 还款金额;
this.还款的日期 = 还款日期;
}
public int 获取待还款金额()
{
return 待还款金额;
}
public int 检验是否还款()
{
if (还款日 == 还款的日期)
return 1;
else
return 0;
}
}
class Delegate
{
public delegate void pay();
public event pay payment;
public void Notify()
{
if (payment != null)
{
Console.WriteLine("触发事件:");
payment();
}
}
}
class Program
{
static void Main(string[] args)
{
Delegate objDelegate = new Delegate();
信用 x1 = new 信用(1000, 27);
信用 x2 = new 信用(2000, 28);
储蓄 c1 = new 储蓄(x1);
储蓄 c2 = new 储蓄(x2);
objDelegate.payment +=
new Delegate.pay(c1.扣款操作);
objDelegate.payment +=
new Delegate.pay(c2.扣款操作);
objDelegate.Notify();
}
}
}
结果展示
gitee仓库:mc/windows实验 (gitee.com)