[英]Pass generic method as parameter to another method
之前已经问过这个问题(我认为),但是看看之前的答案,我仍然无法弄清楚我需要什么。
让我说我有一个私人方法,如:
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
而不是某个特定类型的单个委托,而是一个构造委托的东西。 我认为这只能使用反射或动态类型来完成:
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
替换。
只是想发布另一个我发现有用的解决方案,特别是缓存。 当我从缓存中获取,并且缓存项不存在时,我调用提供的函数来获取数据,缓存它并返回。 但是,这也可以按照您的具体方式使用。
您的其他方法需要类似于此的签名,其中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上找不到任何类似的答案。
考虑使用中间类(或实现接口):
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.");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.