在上一个示例中,使用.NET 自定义的委托定义定义事件,不使用自定义委托。
(1) 事件发布者
使用系统的委托EventHandler 定义事件,目前事件不包含参数。
public class EmployeeSeparator
{
public event EventHandler EmployeeSeparatored;
public void Separate()
{
EmployeeSeparatored?.Invoke(this,EventArgs.Empty);
}
}
事件包含2和参数:object sender, EventArgs e
(2) 事件订阅者
例如,财务部类,使用系统自定义的委托,方法必须和委托一致,所以带有Object参数和EventArgs参数
public class Finance
{
private readonly EmployeeSeparator employeeSeparator;
public Finance(EmployeeSeparator employee)
{
this.employeeSeparator = employee;
employeeSeparator.EmployeeSeparatored += EmployeeSeparator_EmployeeSeparatored;
}
private void EmployeeSeparator_EmployeeSeparatored(object sender, EventArgs e)
{
Console.WriteLine("Finance department: employee separetion process related to Finance department. ");
}
}
IT部门,通样的方式,订阅事件
public class IT
{
private readonly EmployeeSeparator employeeSeparator;
public IT(EmployeeSeparator employee)
{
this.employeeSeparator = employee;
employeeSeparator.EmployeeSeparatored += EmployeeSeparator_EmployeeSeparatored;
}
private void EmployeeSeparator_EmployeeSeparatored(object sender, EventArgs e)
{
Console.WriteLine("IT department: employee separetion process related to IT department. ");
}
}
(3)执行事件
class Program
{
static void Main(string[] args)
{
EmployeeSeparator employeeSeparator=new EmployeeSeparator();
Finance finance=new Finance(employeeSeparator);
IT it = new IT(employeeSeparator);
employeeSeparator.Separate();
Console.ReadKey();
}
}
执行效果如下:
Finance department: employee separetion process related to Finance department.
IT department: employee separetion process related to IT department.
网友评论