我正在编写一个简单的“记忆化”(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 to lots of type parameters)
var cached2 = Memoize<string, int>(DoIt);
}
}
错误信息:
error CS0411: The type arguments for method 'Program.Memoize<T, V>(Func<T, V>)'
cannot be inferred from the usage. Try specifying the type arguments explicitly.
System.Diagnostics
导入、扩展方法以及所有使用Console
的代码。(这不是关于相信编译后代码是否有效,而是关于编译器的处理。)尽管如此,它已经比许多问题要短得多了——总体上做得很好。 - Jon Skeet