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

标签 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;
}

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

最佳答案

不,这种方法行不通。你会试图通过 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);
}

关于c# - 使用参数 Func<T> 重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6096519/

相关文章:

c# - 具有所有元素的 Linq MaxBy?

linq - 如何在 LINQ 中对多个表进行分组

c++ - 从 C DLL 调用重载的 C++ 函数

c# - Restsharp 引用中的版本问题

c# - 使用 Microsoft 的 Visual UI Automation 验证

vb.net - 匿名类型,从 if 语句转换为 AsQueryable,然后进行查询

c++ - 右值的函数重载

c++ - 为什么如果没有显式范围解析,父类的父方法就无法访问?

c# - 我怎样才能使正则表达式起作用?

c# - 如何修复类的名称不自动单数化