18

我想要一个可以执行任何外部方法的类,如下所示:

class CrazyClass
{
  //other stuff

  public AnyReturnType Execute(AnyKindOfMethod Method, object[] ParametersForMethod)
  {
    //more stuff
    return Method(ParametersForMethod) //or something like that
  }
}

这可能吗?是否有接受任何方法签名的委托?

4

4 回答 4

31

您可以通过Func<T>闭包以不同的方式执行此操作:

public T Execute<T>(Func<T> method)
{
   // stuff
   return method();
}

然后调用者可以使用闭包来实现它:

var result = yourClassInstance.Execute(() => SomeMethod(arg1, arg2, arg3));

这里的好处是你允许编译器为你做艰苦的工作,方法调用和返回值都是类型安全的,提供智能感知等。

于 2013-04-02T18:33:48.543 回答
3

我认为在这种情况下你最好使用反射,因为你会得到你在问题中所要求的 - 任何方法(静态或实例),任何参数:

public object Execute(MethodInfo mi, object instance = null, object[] parameters = null)
{
    return mi.Invoke(instance, parameters);
}

System.Reflection.MethodInfo上课。

于 2013-04-02T18:41:04.660 回答
3

有点取决于你为什么要首先这样做......我会使用 Func 泛型来做到这一点,这样 CrazyClass 仍然可以不知道参数。

class CrazyClass
{
    //other stuff

    public T Execute<T>(Func<T> 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<int> method = new Func<int>(()=>Foo(someargs1,someargs2));
        cc.Execute(method);
        //which begs the question why the user wouldn't just do this:
        Foo(someargs1, someargs2);
    }
}
于 2013-04-02T18:48:47.700 回答
0
public static void AnyFuncExecutor(Action a)
{
    try
    {
        a();
    }
    catch (Exception exception)
    {
        throw;
    }
}
于 2014-11-27T08:35:20.937 回答