【发布时间】:2020-06-08 11:45:36
【问题描述】:
我有一个记忆函数“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;
};
}
【问题讨论】:
-
你的
Foo不应该是Fib吗?Foo不应该返回int吗?还是故意返回Func<int, int>?
标签: c# generics memoization