18

次のように、外部メソッドを実行するクラスが必要です。

class CrazyClass
{
  //other stuff

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

これは可能ですか?メソッド署名を受け取るデリゲートはありますか?

4

4 に答える 4

31

Func<T>これは、クロージャーによって別の方法で行うことができます。

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

呼び出し元は、クロージャーを使用してそれを実装できます。

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

ここでの利点は、コンパイラに面倒な作業を任せることができ、メソッド呼び出しと戻り値はすべてタイプ セーフであり、IntelliSense を提供するなどです。

于 2013-04-02T18:33:48.543 に答える
3

そもそもこれを行う理由によって異なります...私は 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);
    }
}
于 2013-04-02T18:48:47.700 に答える
3

この場合、リフレクションを使用する方が良いと思います。質問で求めたものを正確に取得できるためです-任意のメソッド(静的またはインスタンス)、任意のパラメーター:

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

System.Reflection.MethodInfoクラスです。

于 2013-04-02T18:41:04.660 に答える