简体   繁体   English

C#反射委托异常:必须从委托派生

[英]C# Reflection Delegate exception: Must derive from Delegate

I'm trying to understand delegations so I just wrote small try project; 我试图了解代表团,所以我只写了一个小尝试项目。 I have class D: 我有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);
    }
}

and in the main im using: 在主要即时通讯中使用:

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

The method info gets the correct info but the CreateDelegate method throws an exception, saybg that the type must derive from Delegate. 方法信息获取正确的信息,但是CreateDelegate方法抛出异常,该类型必须从Delegate派生。

How can i solve this? 我该如何解决?

If you want to create a delegate for the Func1 method you need to specify the type of the delegate you want to create. 如果要为Func1方法创建委托,则需要指定要创建的委托的类型。 In this case you can use Action<object> : 在这种情况下,您可以使用Action<object>

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

The type you pass to CreateDelegate method is not actually type of the class but type of the function which you will use to call the method. 传递给CreateDelegate方法的类型实际上不是类的类型,而是用于调用该方法的函数的类型。 Therefore it will be delegate type with the same arguments like the original method: 因此,它将是具有与原始方法相同的参数的委托类型:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM