【问题标题】:Unable to Instantiate this Delegate Using Reflection无法使用反射实例化此委托
【发布时间】:2020-05-24 10:34:31
【问题描述】:

我需要将特定委托作为参数传递给method of which I can't change。委托是“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: '无法绑定到目标方法,因为 它的签名与委托类型的签名不兼容。'

即使签名是正确的。

【问题讨论】:

    标签: c# wpf .net-core avaloniaui


    【解决方案1】:

    你的方法不是静态方法,所以你需要使用:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多