Kev*_*ckx 6 c# reflection methods func
我有一个方法(fyi,我正在使用c#),接受一个类型为"Func"的参数,让我们说它是这样定义的:
MethodAcceptingFuncParam(Func<bool> thefunction);
Run Code Online (Sandbox Code Playgroud)
我已经定义了要传递的函数:
public bool DoStuff()
{
return true;
}
Run Code Online (Sandbox Code Playgroud)
我可以很容易地称之为:
MethodAcceptingFuncParam(() => { return DoStuff(); });
Run Code Online (Sandbox Code Playgroud)
这应该是应有的,到目前为止一切顺利.
现在,我想通过反射创建这个方法,而不是传入DoStuff()方法,并将其传递给:
Type containingType = Type.GetType("Namespace.ClassContainingDoStuff");
MethodInfo mi = containingType.GetMethod("DoStuff");
Run Code Online (Sandbox Code Playgroud)
=>这个工作,我可以正确获取methodinfo.
但这就是我被困的地方:我现在想做点什么
MethodAcceptingFuncParam(() => { return mi.??? });
Run Code Online (Sandbox Code Playgroud)
换句话说,我想通过反射传递方法作为MethodAcceptingFuncParam方法的Func参数的值.关于如何实现这一点的任何线索?
Jon*_*eet 11
Delegate.CreateDelegate
如果类型合适,您可以使用.
例如:
var func = (Func<bool>) Delegate.CreateDelegate(typeof(Func<bool>), mi);
MethodAcceptingFuncParam(func);
Run Code Online (Sandbox Code Playgroud)
请注意,如果在大量的执行功能MethodAcceptingFuncParam
,这将是很多比调用速度mi.Invoke
和铸造结果.
归档时间: |
|
查看次数: |
1917 次 |
最近记录: |