【发布时间】:2018-09-01 22:03:26
【问题描述】:
我正在编写一个简单的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.
【问题讨论】:
-
您没有直接在问题中包含完整示例的任何原因?这会让问题变得更好,IMO。
-
@AlexeiS:如果你想让它更短,你可以删除
System.Diagnostics导入和扩展方法,以及所有使用Console的代码。 (这不是关于相信代码在编译后可以工作,而是关于编译器的处理。)不过,它已经比许多问题短得多了——总的来说做得很好。 -
(我还要说,对于问题中的完整示例,您不需要链接,并且在实际代码之前您可能不需要它的 sn-ps。如果您'希望我将其编辑成我认为提出问题的理想方式,让我知道。)
-
(我个人认为这是一个比那个更好的问题 - 我宁愿将一个作为副本关闭而不是反之亦然。)
-
@AlexeiS:完成 - 看看您是否对更改感到满意。
标签: c# generics functional-programming delegates