这个问题之前有人问过(我想),但是通过查看之前的答案我仍然无法弄清楚我需要什么。
假设我有一个私有(private)方法,例如:
private void GenericMethod<T, U>(T obj, U parm1)
我可以这样使用:
GenericMethod("test", 1);
GenericMethod(42, "hello world!");
GenericMethod(1.2345, "etc.");
然后如何将我的 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.");
}
我实在想不通!我需要在 AnotherMethod
中指定什么作为 Action
的通用参数?!
最佳答案
您需要传递给 AnotherMethod
的不是某个特定类型的单个委托(delegate),而是构造委托(delegate)的东西。我认为这只能使用反射或动态类型来完成:
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.");
}
请注意,(t, u) => GenericMethod(t, u)
不能仅替换为 GenericMethod
。
关于c# - 将泛型方法作为参数传递给另一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25170969/