2010-01-09 61 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