我正在编写一个简单的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# 编译器无法在指定示例中将 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)