[英]Which type signature can be used to memoize a generic method in C#?
I have a memoization function 'Memo' and I want to pass generic method 'Foo' to it as a delegate, which type signature can I use to achieve this?我有一个备忘录 function 'Memo' 并且我想将通用方法 'Foo' 作为委托传递给它,我可以使用哪种类型的签名来实现这一点?
public static class Program
{
private static Func<int, int> Foo(int n)
{
return (int x) =>
{
if (n <= 2) return x;
return Foo(n - 1)(1) + Foo(n - 2)(1);
};
}
private static Func<A, B> Memo<A, B>(Func<A, B> f)
{
var cache = new Dictionary<A, B>();
return (A a) =>
{
if (cache.ContainsKey(a))
{
return cache[a];
}
var b = f(a);
cache[a] = b;
return b;
};
}
Methods are implicitly convertible to an Action
/ Func
that matches their signature, so you can do this:方法可以隐式转换为与其签名匹配的
Action
/ Func
,因此您可以这样做:
Func<int, Func<int, int>> foo = Foo;
Memo(foo);
Now that foo
has a type, the generic arguments of Memo
can be inferred.现在
foo
有了类型,可以推断出Memo
的通用 arguments。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.