我需要将特定委托作为参数传递给我无法更改的方法。委托是“ 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:“无法绑定到目标方法,因为它的签名与委托类型的签名不兼容。”
即使签名是正确的。