【问题标题】:Which type signature can be used to memoize a generic method in C#?哪种类型签名可用于记忆 C# 中的泛型方法?
【发布时间】: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&lt;int, int&gt;

标签: c# generics memoization


【解决方案1】:

方法可以隐式转换为与其签名匹配的Action / Func,因此您可以这样做:

Func<int, Func<int, int>> foo = Foo;
Memo(foo);

现在foo 有了类型,可以推断出Memo 的泛型参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    相关资源
    最近更新 更多