而在写程序中,假设程序员就是老板,有两个类分别为主管和员工,而主管小王和员工小张就是两个类的对象实例。员工类有一个方法:玩游戏,同时就有一个玩游戏的事件,他一玩游戏就会激发这个事件。而主管类就是负责处理该事件的,他负责把玩游戏的员工的薪水扣除500。
public class Employee
{
public event PlayGameHandler PlayGame;
private int m_salary;
public Employee()
{
Console.WriteLine("create a employee!");
m_salary = 2000;
}
public int salary
{
get{return this.m_salary;}
set{m_salary=value;}
}
public void EmployeePlayGame()
{
Console.WriteLine("begin play game!");
System.EventArgs e = new System.EventArgs();
OnPlayGame(e);
}
protected virtual void OnPlayGame(EventArgs e)
{
if(PlayGame!=null)
{
PlayGame(this,e);
}
}
}
public delegate void PlayGameHandler(object sender,System.EventArgs e);
public class Manager
{
public Manager()
{
Console.WriteLine("create a manager!");
}
public void CutSalary(object sender,EventArgs e)
{
Console.WriteLine("begin cut");
Employee ely = (Employee)sender;
ely.salary = ely.salary -100;
Console.WriteLine("end cut");
}
}
class Class1
{
/// <summary>
/// 应用程序的主入口点。/// </summary>
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("scene begin..........");
Manager m = new Manager();
Employee ely = new Employee();
ely.PlayGame += new PlayGameHandler(m.CutSalary);
Console.WriteLine("salary is "+ely.salary.ToString()+"");
Console.WriteLine("play game");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
ely.EmployeePlayGame();
Console.WriteLine("salary is "+ely.salary.ToString()+"");
Console.WriteLine("scene is over");
Console.ReadLine();
}
}
浙公网安备 33010602011771号