Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass method, created with reflection, as Func parameter

I've got a method (fyi, I'm using c#), accepting a parameter of type "Func", let's say it's defined as such:

MethodAcceptingFuncParam(Func<bool> thefunction);

I've defined the function to pass in as such:

public bool DoStuff()
{
    return true;
}

I can easily call this as such:

MethodAcceptingFuncParam(() =>  { return DoStuff(); });

This works as it should, so far so good.

Now, instead of passing in the DoStuff() method, I would like to create this method through reflection, and pass this in:

Type containingType = Type.GetType("Namespace.ClassContainingDoStuff");
MethodInfo mi = containingType.GetMethod("DoStuff");

=> this works, I can get the methodinfo correctly.

But this is where I'm stuck: I would now like to do something like

MethodAcceptingFuncParam(() => { return mi.??? });

In other words, I'd like to pass in the method I just got through reflection as the value for the Func param of the MethodAcceptingFuncParam method. Any clues on how to achieve this?

like image 416
Kevin Dockx Avatar asked Dec 11 '09 08:12

Kevin Dockx


2 Answers

You can use Delegate.CreateDelegate, if the types are appropriate.

For example:

var func = (Func<bool>) Delegate.CreateDelegate(typeof(Func<bool>), mi);
MethodAcceptingFuncParam(func);

Note that if the function is executed a lot in MethodAcceptingFuncParam, this will be much faster than calling mi.Invoke and casting the result.

like image 109
Jon Skeet Avatar answered Nov 03 '22 00:11

Jon Skeet


Use Invoke:

MethodAcceptingFuncParam(() => { return (bool)mi.Invoke(null, null); })
like image 37
Adrian Zanescu Avatar answered Nov 02 '22 23:11

Adrian Zanescu