将通用方法作为参数传递给另一个方法

10

这个问题之前已经被问过了(我想),但是查看之前的回答后,我仍然没有能够弄清楚我需要的东西。

假设我有一个私有方法,如下所示:

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的通用参数?!

3个回答

8

您需要传递给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.");
}

请注意,(t, u) => GenericMethod(t, u) 不能简单地替换为 GenericMethod。该语句涉及到IT技术相关内容。

那就是我开始假设的。该死,但还是谢谢! - MadSkunk

3

考虑使用一个中间类(或实现一个接口):

class GenericMethodHolder {
    public void GenericMethod<T, U>(T obj, U parm1) {...};
}

public void AnotherMethod(string parm1, GenericMethodHolder holder)
{
    holder.GenericMethod("test", 1);
    holder.GenericMethod(42, "hello world!");
    holder.GenericMethod(1.2345, "etc.");
}

2

我想分享另一个我发现很有用的解决方法,特别是在缓存方面。当我从缓存中获取数据时,如果缓存项不存在,我调用提供的函数来获取数据,将其缓存并返回。但是,这也可以按照您特定的方式使用。

您的其他方法需要类似于此的签名,其中getItemCallback是要执行的GenericMethod()。出于简洁起见,示例已被清除。

public static T AnotherMethod<T>(string key, Func<T> _genericMethod ) where T : class
{
    result = _genericMethod(); //looks like default constructor but the passed in params are in tact.
    //... do some work here 
    return otherData as T;
}

然后,您将按以下方式调用AnotherMethod()
var result = (Model)AnotherMethod("some string",() => GenericMethod(param1,param2));

我知道这已经是几个月后的事情了,但也许对下一个需要帮助的人有所帮助,因为我忘记了如何做到这一点,并且在SO上找不到任何类似的答案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接