【问题标题】:C# Reflection Delegate exception: Must derive from DelegateC# 反射委托异常:必须从委托派生
【发布时间】:2016-07-01 17:49:00
【问题描述】:

我正在尝试理解委托,所以我只写了一个小尝试项目; 我有D班:

class D
{
    private static void Func1(Object o)
    {
        if (!(o is string)) return;
        string s = o as string;
        Console.WriteLine("Func1 going to sleep");
        Thread.Sleep(1500);
        Console.WriteLine("Func1: " + s);
    }
}

在主要的即时通讯中使用:

 MethodInfo inf = typeof(D).GetMethod("Func1", BindingFlags.NonPublic | BindingFlags.Static);
 Delegate d = Delegate.CreateDelegate(typeof(D), inf);

方法信息得到了正确的信息,但是 CreateDelegate 方法抛出了一个异常,比如类型必须从 Delegate 派生。

我该如何解决这个问题?

【问题讨论】:

  • 嗯,是的...您只能调用CreateDelegate 来创建委托实例。您希望该代码做什么?

标签: c# delegates


【解决方案1】:

如果要为Func1 方法创建委托,则需要指定要创建的委托的类型。在这种情况下你可以使用Action<object>:

MethodInfo inf = typeof(D).GetMethod("Func1", BindingFlags.NonPublic | BindingFlags.Static);
Delegate d = Delegate.CreateDelegate(typeof(Action<object>), inf);

【讨论】:

  • 我得到 System.ArgumentException: '类型必须使用此代码从委托派生:(
  • @SuperJMN - 请添加一个带有可重现示例的新问题。
【解决方案2】:

您传递给CreateDelegate 方法的类型实际上不是类的类型,而是您将用来调用该方法的函数的类型。因此它将是具有与原始方法相同的参数的委托类型:

public delegate void MyDelegate(Object o);
...
MethodInfo inf = typeof(D).GetMethod("Func1", BindingFlags.NonPublic | BindingFlags.Static);
Delegate d = Delegate.CreateDelegate(typeof(MyDelegate), inf);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    相关资源
    最近更新 更多