将泛型方法作为参数传递给另一个方法

Mad*_*unk 9 c# generics delegates .net-4.5

之前已经问过这个问题(我认为),但是看看之前的答案,我仍然无法弄清楚我需要什么.

让我说我有一个私人方法,如:

private void GenericMethod<T, U>(T obj, U parm1)
Run Code Online (Sandbox Code Playgroud)

我可以这样使用:

GenericMethod("test", 1);
GenericMethod(42, "hello world!");
GenericMethod(1.2345, "etc.");
Run Code Online (Sandbox Code Playgroud)

然后我如何将我传递GenericMethod给另一个方法,以便我可以以类似的方式在该方法中调用它?例如:

AnotherMethod("something", GenericMethod);

...

public void AnotherMethod(string parm1, Action<what goes here?> method)
{
    method("test", 1);
    method(42, "hello world!");
    method(1.2345, "etc.");
}
Run Code Online (Sandbox Code Playgroud)

我无法理解这个!我需要做什么指定为通用参数ActionAnotherMethod?!

Ath*_*ari 7

您需要传递AnotherMethod一些特定类型的委托,而不是一个构成委托的东西.我认为这只能使用反射或动态类型来完成:

void Run ()
{
    AnotherMethod("something", (t, u) => GenericMethod(t, u));
}

void GenericMethod<T, U> (T obj, U parm1)
{
    Console.WriteLine("{0}, {1}", typeof(T).Name, typeof(U).Name);
}

void AnotherMethod(string parm1, Action<dynamic, dynamic> method)
{
    method("test", 1);
    method(42, "hello world!");
    method(1.2345, "etc.");
}
Run Code Online (Sandbox Code Playgroud)

注意,(t, u) => GenericMethod(t, u)不能只用替换GenericMethod.