你需要将 Func<T, T1, T2>
转换为 Func<T, T1, T2, T3>
。这并不难,但我不确定这是否是最佳方法。你还有其他通用问题,比如将其转换为字符串的 Model 强制转换。更好的方法可能是像 Cache.Retrieve<TResult>(string cashKey, Func<TResult> missingItemFactory)
这样的东西。然后你可以像这样调用:Cache.Retrieve("model1", () => repository.Get<Model>(myId))
然后在你的方法中只需调用 if (data == null) data = missingItemFactory();
。
无论如何,下面是一个解决方案。
void Main()
{
Func<string, string> f1 = s => "One";
Func<string, string, string> f2 = (s1, s2) => "Two";
Func<string, string, string, string> f3 = (s1, s2, s3) => "Three";
Console.WriteLine(PerformCaching(f1, "one", "f1"));
Console.WriteLine(PerformCaching(f1, "one", "f1"));
Console.WriteLine(PerformCaching(f2, "one", "two", "f2"));
Console.WriteLine(PerformCaching(f2, "one", "two", "f2"));
Console.WriteLine(PerformCaching(f3, "one", "two", "three", "f3"));
Console.WriteLine(PerformCaching(f3, "one", "two", "three", "f3"));
}
public static TResult PerformCaching<TResult, T1>(Func<T1, TResult> func, T1 first, string cacheKey)
{
return PerformCaching<TResult, T1, string, string>((t, t2, t3) => func(t), first, null, null, cacheKey);
}
public static TResult PerformCaching<TResult, T1, T2>(Func<T1, T2, TResult> func, T1 first, T2 second, string cacheKey)
{
return PerformCaching<TResult, T1, T2, string>((t, t2, t3) => func(t, t2), first, second, null, cacheKey);
}
public static TResult PerformCaching<TResult, T1, T2, T3>(Func<T1, T2, T3, TResult> func, T1 first, T2 second, T3 third, string cacheKey)
{
TResult data = Get<TResult>(cacheKey);
if(data == null)
{
Add(cacheKey);
data = func.Invoke(first, second, third);
Update(data);
}
return data;
}
public static T Get<T>(string CashKey) { return default(T); }
public static void Add(string CashKey) { }
public static void Update<T>(T data) { }