使用参数Func 重载方法

我想创建一些接受Func参数的重载方法。 重载方法应该使用参数中定义的最通用类型调用该方法。 下面是我的方法的一个简单示例,以及我想如何调用它们:

public static TResult PerformCaching(Func func, T1 first, string cacheKey) { return PerformCaching((t, _, _) => func, first, null, null, cacheKey); } public static TResult PerformCaching(Func func, T1 first, T2 second, string cacheKey) { return PerformCaching((t, t2, _) => func, first, second, null, cacheKey); } public static TResult PerformCaching(Func func, T1 first, T2 second, T3 third, string cacheKey) { Model data = Get(cacheKey); if(data == null) { Add(cacheKey); data = func.Invoke(first, second, third); Update(data); } return data; } 

是否有可能让它像这样工作? 另一个问题是当func到达最终方法时会发生什么。 它会用一个参数执行它(当第一个方法被调用时)或是用所有三个参数调用它。

不,这种方法不起作用。 您将尝试将Func传递给接受Func – 而这根本不起作用。 我建议换成这样的东西:

 public static TResult PerformCaching(Func func, string cacheKey) { // Do real stuff in here // You may find ConcurrentDictionary helpful... } public static TResult PerformCaching (Func func, T1 first, string cacheKey) { return PerformCaching(() => func(first), cacheKey); } public static TResult PerformCaching (Func func, T1 first, T2 second, string cacheKey) { return PerformCaching(() => func(first, second), cacheKey); } public static TResult PerformCaching (Func func, T1 first, T2 second, T3 third, string cacheKey) { return PerformCaching(() => func(first, second, third), cacheKey); } 

您必须从Func投射到Func 。 这并不难,但我不确定这是最好的方法。 您还有其他一般性问题,例如转换为Model(我将其转换为字符串)。 更好的方法可能是Cache.Retrieve(string cashKey, Func missingItemFactory) 。 然后你会调用Cache.Retrieve("model1", () => repository.Get(myId))然后调用if (data == null) data = missingItemFactory(); 在你的方法里面。

无论如何,解决方案如下。

 void Main() { Func f1 = s => "One"; Func f2 = (s1, s2) => "Two"; Func 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")); } // Define other methods and classes here public static TResult PerformCaching(Func func, T1 first, string cacheKey) { return PerformCaching((t, t2, t3) => func(t), first, null, null, cacheKey); } public static TResult PerformCaching(Func func, T1 first, T2 second, string cacheKey) { return PerformCaching((t, t2, t3) => func(t, t2), first, second, null, cacheKey); } public static TResult PerformCaching(Func func, T1 first, T2 second, T3 third, string cacheKey) { TResult data = Get(cacheKey); if(data == null) { Add(cacheKey); data = func.Invoke(first, second, third); Update(data); } return data; } public static T Get(string CashKey) { return default(T); } public static void Add(string CashKey) { } public static void Update(T data) { }