Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Reflection Delegate exception: Must derive from Delegate

Tags:

c#

delegates

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?

like image 656
Erez Konforti Avatar asked Oct 14 '25 07:10

Erez Konforti


2 Answers

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);
like image 80
Lee Avatar answered Oct 18 '25 01:10

Lee


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);
like image 40
Zbynek Vyskovsky - kvr000 Avatar answered Oct 18 '25 01:10

Zbynek Vyskovsky - kvr000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!