如何解决重载带有参数Func <T>的方法
| 我想创建一些接受Func参数的重载方法。重载的方法应使用参数中定义的最通用的类型来调用该方法。以下是我的方法以及如何调用它们的快速示例:public static TResult PerformCaching<TResult,T1>(Func<T1,TResult> func,T1 first,string cacheKey)
{
return PerformCaching((t,_,_) => func,first,null,cacheKey);
}
public static TResult PerformCaching<TResult,T1,T2>(Func<T1,T2,T2 second,t2,second,T3>(Func<T1,T3,T3 third,string cacheKey)
{
Model data = Get(cacheKey);
if(data == null)
{
Add(cacheKey);
data = func.Invoke(first,third);
Update(data);
}
return data;
}
是否有可能使它像这样工作?另一个问题是当函数到达最终方法时,函数将发生什么情况。它是使用一个参数(调用第一个方法时)执行还是使用所有三个参数调用它。
解决方法
不,这种方法行不通。您将尝试将ѭ1传递给接受ѭ2的方法-这根本行不通。我建议更改为以下内容:
public static TResult PerformCaching<TResult>(Func<TResult> func,string cacheKey)
{
// Do real stuff in here
// You may find ConcurrentDictionary helpful...
}
public static TResult PerformCaching<T1,TResult>
(Func<T1,TResult> func,T1 first,string cacheKey)
{
return PerformCaching(() => func(first),cacheKey);
}
public static TResult PerformCaching<T1,T2,T2 second,string cacheKey)
{
return PerformCaching(() => func(first,second),T3,T3 third,second,third),cacheKey);
}
,您必须从Func<T,T1,T2>
投射到Func<T,T3>
。这并不难,但是我不确定这是最好的方法。您还遇到其他一般性问题,例如强制转换为Model(我将其转换为字符串)。更好的方法可能是类似于Cache.Retrieve<TResult>(string cashKey,Func<TResult> missingItemFactory)
。然后,您将调用ѭ7call,然后在方法内部调用method8ѭ。
无论如何,下面是一个解决方案。
void Main()
{
Func<string,string> f1 = s => \"One\";
Func<string,string,string> f2 = (s1,s2) => \"Two\";
Func<string,string> f3 = (s1,s2,s3) => \"Three\";
Console.WriteLine(PerformCaching(f1,\"one\",\"f1\"));
Console.WriteLine(PerformCaching(f1,\"f1\"));
Console.WriteLine(PerformCaching(f2,\"two\",\"f2\"));
Console.WriteLine(PerformCaching(f2,\"f2\"));
Console.WriteLine(PerformCaching(f3,\"three\",\"f3\"));
Console.WriteLine(PerformCaching(f3,\"f3\"));
}
// Define other methods and classes here
public static TResult PerformCaching<TResult,T1>(Func<T1,string cacheKey)
{
return PerformCaching<TResult,string>((t,t2,t3) => func(t),first,null,cacheKey);
}
public static TResult PerformCaching<TResult,T2>(Func<T1,t3) => func(t,t2),T3>(Func<T1,string cacheKey)
{
TResult data = Get<TResult>(cacheKey);
if(data == null)
{
Add(cacheKey);
data = func.Invoke(first,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) { }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。