以下采用员工玩游戏,老板扣工资的案例:
class Boss
{
private int money = 20;
public void RSalary(int wage)
{
Console.WriteLine("老板发现扣工资{0}¥,剩余{1}", money,wage-money);
}
}
class Employment
{
//为了减少老板的工作,同时低耦合,使用委托代替老板工作
public delegate void PGHandler(int pay);//定义参数委托
public event PGHandler PGevent;//定义事件
//Boss bs = new Boss();
public string name="bin";
public string number="S-0001";
public int wage=5000;
public void PlayGame()
{
Console.WriteLine("员工{0}玩游戏,工号为{1}", name, number);
if (PGevent != null)
{
//如果有对象注册
PGevent(wage);//调用所有注册对象的方法
}
//bs.RSalary();//最原始的,员工玩游戏就调用老板类的扣工资方法。
}
public void Chat()
{
Console.WriteLine("员工{0}QQ聊天,工号为{1}", name,number);
if (PGevent != null)
{
PGevent(wage);
}
//bs.RSalary();
}
}
class Program
{
static void Main(string[] args)
{
Employment em = new Employment();
Boss bs = new Boss();
em.PGevent += bs.RSalary;//注册方法
em.PlayGame();//玩游戏,会自动调用注册过的扣工资方法
em.Chat();
Console.ReadLine();
}
}
}