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

时间:2014-08-06 21:58:33

标签: c# generics delegates .net-4.5

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

假设我有一个私人方法,如:

private void GenericMethod<T, U>(T obj, U parm1)

我可以这样使用:

GenericMethod("test", 1);
GenericMethod(42, "hello world!");
GenericMethod(1.2345, "etc.");

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

AnotherMethod("something", GenericMethod);

...

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

我无法理解这个!我需要在Action中指定AnotherMethod的通用参数?!

3 个答案:

答案 0 :(得分: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.");
}

请注意,(t, u) => GenericMethod(t, u)不能仅用GenericMethod替换。

答案 1 :(得分: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上找不到任何类似的答案。

答案 2 :(得分:2)

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

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.");
}