Dan*_*ler 16 c# generics reflection delegates method-signature
我想要一个将执行任何外部方法的类,如下所示:
class CrazyClass
{
//other stuff
public AnyReturnType Execute(AnyKindOfMethod Method, object[] ParametersForMethod)
{
//more stuff
return Method(ParametersForMethod) //or something like that
}
}
Run Code Online (Sandbox Code Playgroud)
这可能吗?是否有代理人采用任何方法签名?
Ree*_*sey 30
你可以用不同的方式Func<T>和闭包来做到这一点:
public T Execute<T>(Func<T> method)
{
// stuff
return method();
}
Run Code Online (Sandbox Code Playgroud)
然后调用者可以使用闭包来实现它:
var result = yourClassInstance.Execute(() => SomeMethod(arg1, arg2, arg3));
Run Code Online (Sandbox Code Playgroud)
这里的优点是你允许编译器为你做艰苦的工作,方法调用和返回值都是类型安全的,提供intellisense等.