超载参数Func键℃的方法; T> [英] Overloading a method with parameter Func<T>

查看:99
本文介绍了超载参数Func键℃的方法; T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一些重载方法而接受一个Func键参数。重载方法调用的方法与参数定义的最通用的类​​型。下面是我的方法一个简单的例子,我想怎么称呼他们:

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



有没有可能得到它的工作是这样?另外一个问题是发生了什么事的FUNC,当它到达最后一个方法。将它与一个参数执行它(当第一个方法被调用),或者是它与所有三个参数调用。

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.

推荐答案

没有,这种做法是行不通的。你会试图通过一个 Func键< T1,TResult> 来接受的方法的 Func键< T1,T2,T3,TResult> - 这根本不起作用。我建议改变的东西是这样的:

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);
}

这篇关于超载参数Func键℃的方法; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆