I would like to create a few overloaded methods which accept a Func parameter. The overloaded methods should call the method with the most generic types defined in the parameter. Below is a quick example of my methods, and how I would like to call them:
public static TResult PerformCaching<TResult, T1>(Func<T1, TResult> func, T1 first, string cacheKey)
{
return PerformCaching((t, _, _) => func, first, null, null, cacheKey);
}
public static TResult PerformCaching<TResult, T1, T2>(Func<T1, T2, TResult> func, T1 first, T2 second, string cacheKey)
{
return PerformCaching((t, t2, _) => func, 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)
{
Model data = Get(cacheKey);
if(data == null)
{
Add(cacheKey);
data = func.Invoke(first, second, third);
Update(data);
}
return data;
}
Would it be possible to get it working like this? Another question is what is happening to the func, when it reaches the final method. Would it execute it with one parameter (when the first method is called) or is it called with all three parameters.
Method overloading can be achieved by the following: By changing the number of parameters in a method. By changing the order of parameters in a method. By using different data types for parameters.
In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading. For example: void func() { ... }
The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return type. It will throw a compile-time error. If both methods have the same parameter types, but different return type, then it is not possible.
No, that approach wouldn't work. You'd be trying to pass a Func<T1, TResult>
to a method accepting a Func<T1, T2, T3, TResult>
- and that simply doesn't work. I would suggest changing to something like this:
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, TResult>
(Func<T1, T2, TResult> func, T1 first, T2 second, string cacheKey)
{
return PerformCaching(() => func(first, second), cacheKey);
}
public static TResult PerformCaching<T1, T2, T3, TResult>
(Func<T1, T2, T3, TResult> func, T1 first, T2 second, T3 third,
string cacheKey)
{
return PerformCaching(() => func(first, second, third), cacheKey);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With