使用参数Func <T>重载方法

Chr*_*anV 5 c# linq overloading

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 7

不,这种方法不起作用.你试图将Func<T1, TResult>一个方法传递给一个接受一个方法Func<T1, T2, T3, TResult>- 而这根本不起作用.我建议换成这样的东西:

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);
}
Run Code Online (Sandbox Code Playgroud)