4

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?

Erez Konforti
  • 243
  • 5
  • 19
  • Well yes... you can only call `CreateDelegate` to create instances of delegates. What did you expect that code to do? – Jon Skeet Jul 01 '16 at 09:44

2 Answers2

7

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);
Lee
  • 142,018
  • 20
  • 234
  • 287
1

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);
Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43