Action <object,runworkercompletedeventargs =“”>和RunWorkerCompletedEventHandler之间的区别

时间:2015-11-06 17:39:37

标签: c# events delegates

我正在使用BackgroundWorker。 我试着注册一个Action的处理程序,如下所示:

   public void Backup(Action<object, RunWorkerCompletedEventArgs> completionEventHandler)
   {
      _backupWorker.RunWorkerCompleted += completionEventHandler;
   }

但是,我收到了错误:

   Cannot implicitly convert type 
   'System.Action<object,System.ComponentModel.RunWorkerCompletedEventArgs>' to
   'System.ComponentModel.RunWorkerCompletedEventHandler'

据我所知,

   Action<object,System.ComponentModel.RunWorkerCompletedEventArgs>

只是一个

   delegate void Action(object,System.ComponentModel.RunWorkerCompletedEventArgs)

和RunWorkerCompletedEventHandler只是

   delegate void RunWorkerCompletedEventHandler(object sender, RunWorkerCompletedEventArgs e)

因此,它们都是相同类型的委托(相同的参数和相同的返回类型)。那么为什么我不能使用需要RunWorkerCompletedEventHandler的Action呢?

谢谢!

1 个答案:

答案 0 :(得分:2)

不同委托类型的委托对象永远不可转换,即使委托签名完全相同。简单的解决方案是在触发事件时使用lambda表达式来调用委托。像这样:

public void Backup(Action<object, RunWorkerCompletedEventArgs> completionEventHandler) {
    _backupWorker.RunWorkerCompleted += (s, ea) => completionEventHandler(s, ea);
}