相关疑难解决方法(0)

为什么我必须为Func参数显式指定我的类型参数?

我正在编写一个简单的Memoize帮助程序,它允许缓存方法结果,而不是每次都计算它们.但是,当我尝试传入一个方法时Memoize,编译器无法确定类型参数.从我的方法签名中不是很明显吗?有没有解决的办法?

示例代码:

using System;
using System.Collections.Concurrent;

public static class Program
{
    public static Func<T, V> Memoize<T, V>(Func<T, V> f)
    {
        var cache = new ConcurrentDictionary<T, V>();
        return a => cache.GetOrAdd(a, f);
    }

    // This is the method I wish to memoize
    public static int DoIt(string a) => a.Length;        

    static void Main()
    {
        // This line fails to compile (see later for error message)
        var cached1 = Memoize(DoIt);

        // This works, but is ugly (and doesn't scale …
Run Code Online (Sandbox Code Playgroud)

c# generics delegates functional-programming

5
推荐指数
1
解决办法
243
查看次数

C# 泛型委托类型推断

为什么 C# 编译器无法在指定示例中将 T 推断为 int?

void Main()
{
    int a = 0;
    Parse("1", x => a = x);
    // Compiler error:
    // Cannot convert expression type 'int' to return type 'T'
}

public void Parse<T>(string x, Func<T, T> setter)
{
    var parsed = ....
    setter(parsed);
}
Run Code Online (Sandbox Code Playgroud)

c# generics delegates

3
推荐指数
1
解决办法
924
查看次数

标签 统计

c# ×2

delegates ×2

generics ×2

functional-programming ×1