Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#委托问题-这段代码到底做了什么?_C#_C# 3.0_Delegates - Fatal编程技术网

C#委托问题-这段代码到底做了什么?

C#委托问题-这段代码到底做了什么?,c#,c#-3.0,delegates,C#,C# 3.0,Delegates,谁能给我解释一下下面这行C代码的作用吗 public event EventHandler<DataEventArgs<BusinessEntities.Employee>> EmployeeSelected = delegate { }; 此位: delegate {} 只创建适当类型的“无操作”委托。然后将该委托分配给事件的支持变量。这是一种避免在引发事件时进行空检查的简单方法-您总是至少有一个处理程序,即无操作处理程序 这意味着此代码可以很简单: Employe

谁能给我解释一下下面这行C代码的作用吗

public event EventHandler<DataEventArgs<BusinessEntities.Employee>> EmployeeSelected = delegate { };
此位:

delegate {}
只创建适当类型的“无操作”委托。然后将该委托分配给事件的支持变量。这是一种避免在引发事件时进行空检查的简单方法-您总是至少有一个处理程序,即无操作处理程序

这意味着此代码可以很简单:

EmployeeSelected(this, new DataEventArgs<BusinessEntities.Employee>(selected));
EmployeeSelected(这是新的DataEventArgs(selected));
而不是:

EventHandler<DataEventArgs<BusinessEntities.Employee>> handler =EmployeeSelected;
if (handler != null)
{
    handler(this, new DataEventArgs<BusinessEntities.Employee>(selected));
}
EventHandler=EmployeeSelected;
if(处理程序!=null)
{
处理程序(此,新DataEventArgs(选定));
}

它将其设置为一个基本上不做任何事情的匿名方法。为什么我不确定,也许是为了避免一个支票或某事,但是我会认为这很草率。

这只是空对象模式——我不明白你为什么认为草率。在我们公司,我们把它称为“空委托模式”。
EventHandler<DataEventArgs<BusinessEntities.Employee>> handler =EmployeeSelected;
if (handler != null)
{
    handler(this, new DataEventArgs<BusinessEntities.Employee>(selected));
}