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

标签 c# generics delegates .net-4.5

这个问题之前有人问过(我想),但是通过查看之前的答案我仍然无法弄清楚我需要什么。

假设我有一个私有(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/

相关文章:

C# 使用泛型类型转换自定义对象

c# - 当类型已知时,类型 'T' 不能用作泛型类型或方法错误中的类型参数

c# - 如何用反射识别 lambda 闭包

ios - 来自 UITableViewCell 的委托(delegate)不起作用

c# - DateTime.Now 到底什么时候更新?

c# - 将类型 `System.Collections.IEnumerator` 转换为 `System.Collections.Generic.IEnumerator`

c# - ServiceStack.DataAnnotations 缺少属性定义?

c# - 单击 Card Action - Bot Framework 时如何调用特定回调

Java嵌套泛型类型

c# - 将事件处理程序的定义作为 lambda 表达式传递