C# 将eventhandler转换为委托?
我见过pluralsight上的一些程序员在执行之前将其EventHandler转换为委托。为什么这是一个好的做法?通常我只调用事件而不强制转换C# 将eventhandler转换为委托?,c#,event-handling,eventhandler,C#,Event Handling,Eventhandler,我见过pluralsight上的一些程序员在执行之前将其EventHandler转换为委托。为什么这是一个好的做法?通常我只调用事件而不强制转换 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication13 { public class Mediator
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication13
{
public class Mediator
{
public event EventHandler<EmployeeArgs> EmployeeEventChange;
private static readonly Mediator _Instance = new Mediator();
private Mediator() { }
public static Mediator GetInstance()
{
return _Instance;
}
public void OnEmployeeHandler(Employee e)
{
var EmployeeEventDelegate = EmployeeEventChange as EventHandler<EmployeeArgs>;
if (EmployeeEventDelegate != null)
{
EmployeeEventDelegate(this, new EmployeeArgs()
{
Employee = e
});
}
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
命名空间控制台应用程序13
{
公共类调解人
{
公共事件处理程序EmployeeEventChange;
私有静态只读中介_Instance=new Mediator();
私有中介(){}
公共静态中介程序GetInstance()
{
返回_实例;
}
公共作废OneEmployeeHandler(员工e)
{
var EmployeeEventDelegate=EmployeeEventChange作为事件处理程序;
if(EmployeeEventDelegate!=null)
{
EmployeeEventDelegate(此,新EmployeeArgs()
{
雇员=e
});
}
}
}
}
强制转换(imo)是毫无意义的,但它被分配给局部变量这一事实有一个值——它使调用线程安全。你可以准备更多
如果您没有将事件处理程序分配给局部变量,并且有人在
!=null
检查并调用,您将得到一个异常。通过制作副本,您可以确保没有人在null
检查和调用之间更改您所知道的订阅者列表。EmployeeEventChange
已经是EventHandler
类型,因此我不确定您为什么要转换它。这不仅仅是说转换毫无意义的观点。强制转换是毫无意义的,因为类型完全相同,因此它不会改变任何东西。这与这样做是一样的inti=(int)5代码>。无论如何,该强制转换可能会被编译器删除。