委托任何方法类型 – C#
我想要一个将执行任何外部方法的类,如下所示:
class CrazyClass { //other stuff public AnyReturnType Execute(AnyKindOfMethod Method, object[] ParametersForMethod) { //more stuff return Method(ParametersForMethod) //or something like that } }
这可能吗? 是否有代理人采用任何方法签名?
您可以通过Func
和闭包以不同的方式执行此操作:
public T Execute(Func method) { // stuff return method(); }
然后调用者可以使用闭包来实现它:
var result = yourClassInstance.Execute(() => SomeMethod(arg1, arg2, arg3));
这里的优点是你允许编译器为你做艰苦的工作,方法调用和返回值都是类型安全的,提供intellisense等。
有点取决于你为什么要这样做…我会使用Funcgenerics做到这一点,以便CrazyClass仍然可以不知道参数。
class CrazyClass { //other stuff public T Execute(Func Method) { //more stuff return Method();//or something like that } } class Program { public static int Foo(int a, int b) { return a + b; } static void Main(string[] args) { CrazyClass cc = new CrazyClass(); int someargs1 = 20; int someargs2 = 10; Func method = new Func (()=>Foo(someargs1,someargs2)); cc.Execute(method); //which begs the question why the user wouldn't just do this: Foo(someargs1, someargs2); } }
我认为你最好在这种情况下使用reflection,因为你将得到你在问题中所要求的 – 任何方法(静态或实例),任何参数:
public object Execute(MethodInfo mi, object instance = null, object[] parameters = null) { return mi.Invoke(instance, parameters); }
它是System.Reflection.MethodInfo
类。
public static void AnyFuncExecutor(Action a) { try { a(); } catch (Exception exception) { throw; } }