-->

委派任何方法类型 - C#(Delegate for any method type - C#)

2019-08-19 02:51发布

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

class CrazyClass
{
  //other stuff

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

这可能吗? 有没有采取任何方法签名的委托?

Answer 1:

您可以通过此做一个不同的方式Func<T>和关闭:

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

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

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

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



Answer 2:

有点取决于你为什么要这样做摆在首位...我会使用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);
    }
}


Answer 3:

我想你最好使用在这种情况下的反射,你会得到你的问题问到底是什么了 - 任何方法(静态或实例),任何参数:

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

这是System.Reflection.MethodInfo类。



Answer 4:

public static void AnyFuncExecutor(Action a)
{
    try
    {
        a();
    }
    catch (Exception exception)
    {
        throw;
    }
}


文章来源: Delegate for any method type - C#