开发者

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?


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.


Use Invoke:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜