将通过反射创建的方法作为 Func 参数传递
我有一个方法(仅供参考,我使用的是 c#),接受“Func”类型的参数,假设它是这样定义的:
MethodAcceptingFuncParam(Func<bool> thefunction);
我已经定义了要传入的函数:
public bool DoStuff()
{
return true;
}
我可以轻松地将其称为这样:
MethodAcceptingFuncParam(() => { return DoStuff(); });
这按预期工作,到目前为止一切顺利。
现在,我不想传入 DoStuff() 方法,而是想通过反射创建此方法,并将其传入:
Type containingType = Type.GetType("Namespace.ClassContainingDoStuff");
MethodInfo mi = containingType.GetMethod("DoStuff");
=>这有效,我可以正确获取方法信息。
但这就是我陷入困境的地方:我现在想做类似的事情
MethodAcceptingFuncParam(() => { return mi.??? });
换句话说,我想将刚刚通过反射获得的方法作为 MethodAcceptingFuncParam 方法的 Func 参数的值传递。有关如何实现这一目标的任何线索?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
Delegate.CreateDelegate
,如果类型合适。例如:
请注意,如果在
MethodAcceptingFuncParam
中多次执行该函数,这将比调用mi.Invoke
并转换结果快得多 。You can use
Delegate.CreateDelegate
, if the types are appropriate.For example:
Note that if the function is executed a lot in
MethodAcceptingFuncParam
, this will be much faster than callingmi.Invoke
and casting the result.使用调用:
Use Invoke: