.net 使用反射添加事件处理程序时引发TargetException

.net 使用反射添加事件处理程序时引发TargetException,.net,reflection,asynchronous,delegates,backgroundworker,.net,Reflection,Asynchronous,Delegates,Backgroundworker,我想在WebClient对象回调时调用BackgroundWorker线程 我的目标是在此BackgroundWorker上运行的方法不是固定的,因此我需要以编程方式以指定的方法为目标 为实现这一目标: 传递给WebClient的事件args对象上的属性之一详细说明了应获取的方法(例如UserState.ToString())。该方法正如期获得 然后我希望做的是将这个获得的方法作为委托添加到BackgroundWorker.DoWork事件中 // this line gets the targ

我想在WebClient对象回调时调用BackgroundWorker线程

我的目标是在此BackgroundWorker上运行的方法不是固定的,因此我需要以编程方式以指定的方法为目标

为实现这一目标: 传递给WebClient的事件args对象上的属性之一详细说明了应获取的方法(例如UserState.ToString())。该方法正如期获得

然后我希望做的是将这个获得的方法作为委托添加到BackgroundWorker.DoWork事件中

// this line gets the targeted delegate method from the method name
var method = GetType().GetMethod(e.UserState.ToString(), BindingFlags.NonPublic | BindingFlags.Instance);
if (method != null)
{
    // get the DoWork delegate on the BackgroundWorker object
    var eventDoWork = _bw.GetType().GetEvent("DoWork", BindingFlags.Public | BindingFlags.Instance);
    var tDelegate = eventDoWork.EventHandlerType;
    var d = Delegate.CreateDelegate(tDelegate, this, method);

    // add the targeted method as a handler for the DoWork event
    var addHandler = eventDoWork.GetAddMethod(false);
    Object[] addHandlerArgs = { d };
    addHandler.Invoke(this, addHandlerArgs);

    // now invoke the targeted method on the BackgroundWorker thread
    if (_bw.IsBusy != true)
    {
        _bw.RunWorkerAsync(e);
    }
}
由于某种原因,会在线路上抛出TargetException

addHandler.Invoke(this, addHandlerArgs);
异常消息是

对象与目标类型不匹配

我正在构建代码的方法的签名是

private void GotQueueAsync(object sender, DoWorkEventArgs e)
这与BackgroundWorker.DoWork事件处理程序的签名匹配

有人能解释一下我做错了什么,或者为什么我不能以编程方式添加这个处理程序方法吗


[如果有问题,这是一个WP7应用程序。]

您传递的
不正确:

addHandler.Invoke(this, addHandlerArgs);
带有事件的对象不是
this
(尽管
this
具有处理程序)-它应该是
\u bw

addHandler.Invoke(_bw, addHandlerArgs);
但更简单地说:

var d = (DoWorkEventHandler)Delegate.CreateDelegate(
    typeof(DoWorkEventHandler), this, method);
_bw.DoWork += d;

或者至少使用
EventInfo.AddEventHandler

是的,这两种建议都很有效。这让我省去了很多麻烦。谢谢