简体   繁体   中英

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:

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.

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. In this case you can use 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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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