Question

I want to have a class that will execute any external method, like this:

class CrazyClass
{
  //other stuff

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

Is this possible? Is there a delegate that takes any method signature?

Was it helpful?

Solution

You can do this a different way by Func<T> and closures:

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

The caller can then use closures to implement it:

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

The advantage here is that you allow the compiler to do the hard work for you, and the method calls and return value are all type safe, provide intellisense, etc.

OTHER TIPS

I think you are better off using reflections in this case, as you will get exactly what you asked for in the question - any method (static or instance), any parameters:

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

It's System.Reflection.MethodInfo class.

Kinda depends on why you want to do this in the first place...I would do this using the Func generic so that the CrazyClass can still be ignorant of the parameters.

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);
    }
}
public static void AnyFuncExecutor(Action a)
{
    try
    {
        a();
    }
    catch (Exception exception)
    {
        throw;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top