views:

193

answers:

3

Hello,

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?

+4  A: 

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.

Jon Skeet
A: 

Use Invoke:

MethodAcceptingFuncParam(() => { return (bool)mi.Invoke(null, null); })
AZ