我正在尝试将方法转换为内部(和嵌套)委托类型。问题是因为它是内部的,Delegate.CreateDelegate
失败并引发异常。
System.ArgumentException:
无法绑定到目标方法,因为其签名或安全透明度与委托类型的方法不兼容。
以下是我试图完成此任务的相关代码。
// The method to convert to the internal delegate type
private void OnEnterMenuMode(object sender, EventArgs e);
// The internal nested delegate type
public sealed class KeyboardNavigation {
internal delegate bool EnterMenuModeEventHandler(object sender, EventArgs e);
// The code used to create the delegate
object instance; // Owner of OnEnterMenuMode
EventInfo eventInfo; // The internal event
Delegate.CreateDelegate(eventInfo.EventHandlerType, instance,
((Action<object,EventArgs>)method).Method);
答案 0 :(得分:0)
我设法通过ConstructorInfo
和函数IntPtr
构建代理来找到解决方案。
object instance; // Owner of OnEnterMenuMode
EventInfo eventInfo; // The internal event
// There is only one constructor for a `Delegate`, so this
// just makes it easier to find without all of the arguments.
ConstructorInfo constructor = eventInfo.EventHandlerType.GetConstructors()[0];
// Delegate constructors take arguments of `(object, IntPtr)`.
// Where `IntPtr` is a pointer to the method.
IntPtr ptr = ((Action<object,EventArgs>)method)
.Method.MethodHandle.GetFunctionPointer();
return (Delegate) constructor.Invoke(new object[] { instance, ptr });