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.
什麼是錯?這些方法駐留在不同的非靜態公共類中。任何幫助將不勝感激。
注意:這些方法將有參數和返回值。據我所知Action
和Action<T>
,這不會是一個選項。
首先,感謝您的回答。真棒!帶有返回類型的'delegateMethod'簽名在帖子中是一個疏忽。我一直在簡化整個事情,只是忘了說明。 但是,這絕對是我需要的。我確信我實際上已經嘗試過傳遞目標對象 - 但是,這次我們已經做對了。再次感謝... – IAbstract 2010-01-09 10:50:18