2010-01-09 64 views
1

我有一个实现构建委托处理程序集合。建设代表处理程序集合

public class DelegateHandler 
    { 
      internal delegate object delegateMethod(object args); 
      public IntPtr PublishAsyncMethod(MethodInfo method, MethodInfo callback) 
      { 
       RuntimeMethodHandle rt; 

       try 
       { 
        rt = method.MethodHandle; 
        delegateMethod dMethod = (delegateMethod)Delegate.CreateDelegate 
         (typeof(delegateMethod), method.ReflectedType, method, true); 
        AsyncCallback callBack = (AsyncCallback)Delegate.CreateDelegate 
         (typeof(AsyncCallback), method.ReflectedType, callback, true); 

        handlers[rt.Value] = new DelegateStruct(dMethod, callBack); 
        return rt.Value; 
       } 
       catch (System.ArgumentException ArgEx) 
       { 
        Console.WriteLine("*****: " + ArgEx.Source); 
        Console.WriteLine("*****: " + ArgEx.InnerException); 
        Console.WriteLine("*****: " + ArgEx.Message); 
       } 

       return new IntPtr(-1); 
      } 
    } 

我发布使用下列内容:

ptr = DelegateHandler.Io.PublishAsyncMethod(
    this.GetType().GetMethod("InitializeComponents"), 
    this.GetType().GetMethod("Components_Initialized")); 

而且我从创建的委托方法:

public void InitializeComponents(object args) 
    { 
      // do stuff; 
    } 

而且回调方法:

public void Components_Initialized(IAsyncResult iaRes) 
{ 
     // do stuff; 
} 

现在,我已经看过一个t this了解我可能做错了什么。 CreateDelegate(...)使我得到:

*****: mscorlib 
*****: 
*****: Error binding to target method. 

什么是错?这些方法驻留在不同的非静态公共类中。任何帮助将不胜感激。

注意:这些方法将有参数和返回值。据我所知ActionAction<T>,这不会是一个选项。

回答

1

有2个问题。

首先,您将不正确的参数传递给CreateDelegate。由于您绑定了实例方法,因此您需要传递代理将绑定到的实例,但是您传递的是​​3210而不是对声明为InitializeComponentsComponents_Initialized的类的对象的引用。

二,InitializeComponents的签名与代表dMethod的声明不符。代表有object返回类型,但InitializeComponents返回void

下面应该工作:

// return type changed to void to match target. 
internal delegate void delegateMethod(object args); 

// obj parameter added 
public static void PublishAsyncMethod(object obj, MethodInfo method, MethodInfo callback) 
{ 
    delegateMethod dMethod = (delegateMethod)Delegate.CreateDelegate 
     (typeof(delegateMethod), obj, method, true); 

    AsyncCallback callBack = (AsyncCallback)Delegate.CreateDelegate 
     (typeof(AsyncCallback), obj, callback); 

} 

DelegateHandler.PublishAsyncMethod(
    this, // pass this pointer needed to bind instance methods to delegates. 
    this.GetType().GetMethod("InitializeComponents"), 
    this.GetType().GetMethod("Components_Initialized")); 
+0

首先,感谢您的回答。真棒!带有返回类型的'delegateMethod'签名在帖子中是一个疏忽。我一直在简化整个事情,只是忘了说明。 但是,这绝对是我需要的。我确信我实际上已经尝试过传递目标对象 - 但是,这次我们已经做对了。再次感谢... – IAbstract 2010-01-09 10:50:18