1

我需要将特定委托作为参数传递给我无法更改的方法。委托是“ System.Windows.Interop.HwndSourceHook ”,它是 PresentationCore.dll 的一部分。它必须是那个委托,它不能是具有相同签名的通用委托。而且 AFIAK 您不能将代表从一种类型转换为另一种类型。

这是委托的方法:

public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    if (condition) {// Do stuff };
    return IntPtr.Zero;
}

在编译时加载程序集时一切正常。但是,我将项目移植到 Avalonia 框架,并且必须在运行时加载这个特定的程序集,所以我必须使用反射。

我认为这应该工作......

Assembly dll = Assembly.LoadFrom(@"C:\Temp\PresentationCore.dll");
Type hwndSourceHookDelegateType = dll.GetType("System.Windows.Interop.HwndSourceHook"); 
MethodInfo wndProc = typeof(MyClass).GetMethod(nameof(this.WndProc));
Delegate del = Delegate.CreateDelegate(hwndSourceHookDelegateType, wndProc)

...但最后一行抛出:

System.ArgumentException:“无法绑定到目标方法,因为它的签名与委托类型的签名不兼容。”

即使签名是正确的。

4

1 回答 1

3

您的方法不是静态方法,因此您需要使用:

Delegate del = Delegate.CreateDelegate(hwndSourceHookDelegateType, this, wndProc);

或者

IntPtr del = (IntPtr) Delegate.CreateDelegate(hwndSourceHookDelegateType, this, wndProc);

将“this”传递给第二个参数将允许该方法绑定到当前对象上的实例方法

于 2020-05-24T12:03:17.053 回答