Delegate for any method type - C#
Asked Answered
S

4

20

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?

Senility answered 2/4, 2013 at 18:31 Comment(1)
How will you know what parameters to pass to it? What should happen if you guess wrong as to the number and type of parameters?Bissau
J
32

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.

Julijulia answered 2/4, 2013 at 18:33 Comment(3)
Can we do this in the constructor of CrazyClass? If so, how?Recession
@Recession - You'd need to make CrazyClass generic if you wanted to do that.Julijulia
This requires the arguments to the method to be known and bound to the lambda when calling Execute(...). It cannot be used to run any method with any parameters.Outrank
G
3

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.

Goatee answered 2/4, 2013 at 18:41 Comment(0)
M
3

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);
    }
}
Modulator answered 2/4, 2013 at 18:48 Comment(0)
N
0
public static void AnyFuncExecutor(Action a)
{
    try
    {
        a();
    }
    catch (Exception exception)
    {
        throw;
    }
}
Nd answered 27/11, 2014 at 8:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.