I\'ve noticed that the Delegate class has a Target property, that (presumably) returns the instance the delegate method will execute on. I want to do something like this:
It is possible with Delegate.CreateDelegate, exactly with the overload with the signature:
CreateDelegate (Type, object, MethodInfo)
If you specify "null" for the second parameter (target) then you have to put an extra parameter into the delegate type, that specifies the instance type, and when you invoke the delegate, the instance has to be passed as first argument, followed by the "real" parameters of the method.
class Test
{
public int AddStrings(string a, string b)
{
return int.Parse(a) + int.Parse(b);
}
static void Main()
{
var test = new Test();
var methodInfo = test.GetType().GetMethod("AddStrings");
// note the first extra parameter of the Func, is the owner type
var delegateType = typeof(Func);
var del = Delegate.CreateDelegate(delegateType, null, methodInfo);
var result = (int)del.DynamicInvoke(test, "39", "3");
}
}