Delegate for any method type - C#

2019-02-08 10:49发布

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?

4条回答
劳资没心,怎么记你
2楼-- · 2019-02-08 11:19

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.

查看更多
Bombasti
3楼-- · 2019-02-08 11:33
public static void AnyFuncExecutor(Action a)
{
    try
    {
        a();
    }
    catch (Exception exception)
    {
        throw;
    }
}
查看更多
SAY GOODBYE
4楼-- · 2019-02-08 11:43

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.

查看更多
▲ chillily
5楼-- · 2019-02-08 11:44

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);
    }
}
查看更多
登录 后发表回答