委托任何方法类型- c#

本文关键字:类型 方法 任何 | 更新日期: 2023-09-27 18:07:17

我想有一个类,将执行任何外部方法,像这样:

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

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

委托任何方法类型- c#

您可以通过Func<T>和闭包的不同方式做到这一点:

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

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

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

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

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

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

System.Reflection.MethodInfo级。

这取决于你为什么要这样做…我将使用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);
    }
}
public static void AnyFuncExecutor(Action a)
{
    try
    {
        a();
    }
    catch (Exception exception)
    {
        throw;
    }
}