简体   繁体   English

C# 中可以使用哪种类型签名来记忆泛型方法?

[英]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.

相关问题 C#从方法签名实例化泛型类型 - C# instantiate generic type from method signature C#-返回具体类型的泛型方法调用方法? - C# - Generic method calling method which returns concrete type? C#:具有未知签名的通用方法表达式 - C#: Generic method expression with unknown signature 通用C#方法,返回指定类型的列表 - Generic C# method which returns lists of the specified type 通用方法类型不能用作通用类的通用类型 - Generic method type can't be used as generic type for generic class 为什么C#无法从非泛型静态方法的签名推断泛型类型参数类型? - Why is C# unable to infer the generic type argument type form a non-generic static method's signature? CS0311 C# 该类型不能用作泛型类型或方法中的类型参数“TContext”。 EntityFrameworkCore - CS0311 C# The type cannot be used as type parameter 'TContext' in the generic type or method. EntityFrameworkCore 无法推断通用tostring方法中的类型C# - Can't infer type in generic tostring method C# 我如何在C#中调用通用T类型方法 - How can i call generic T type method in c# 给定一个包含类名称的字符串,然后我如何使用该类作为C#中的类型参数来调用泛型方法? - Given a string which holds the name of a class, how can I then call a generic method using that class as the type parameter in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM