通用函数包装器

Generic Function wrapper

我有很多不同内容的函数,但是里面的参数和try catch都差不多。有没有把函数包装起来,减少冗余代码。

ResponseStatus GetPotatoList(GetPotatosRequest requestParam, out GetPotatosResponse response, out ResponseErrorType errorType)
{
    ResponseStatus status = ResponseStatus.Fail;
    response = new GetPotatosResponse();

    //To Do

    try
    {

        //To Do

        status = ResponseStatus.Success;
    }
    catch(CustomException ex)
    {
        errorType = ResponseErrorType.CustomError;
    }
    catch(TimeoutException ex)
    {
        errorType = ResponseErrorType.Timeout;
    }
    catch(Exception ex)
    {
        errorType = ResponseErrorType.GeneralFailure;
    }

    return status;
}

您可以将 Action 传递给您的方法。

ResponseStatus GetPotatoList(Action action1, Action action2, GetPotatosRequest requestParam, out GetPotatosResponse response, out ResponseErrorType errorType)
{
    ResponseStatus status = ResponseStatus.Fail;
    response = new GetPotatosResponse();

    action1();

    try
    {
        action2();
        status = ResponseStatus.Success;
    }
    catch(CustomException ex)
    {
        errorType = ResponseErrorType.CustomError;
    }
    catch(TimeoutException ex)
    {
        errorType = ResponseErrorType.Timeout;
    }
    catch(Exception ex)
    {
        errorType = ResponseErrorType.GeneralFailure;
    }

    return status;
}

然后使用它:

var response = GetPotatoList(
    () => doSomething(),
    () => doSomethingElse(),
    requestParam,
    out response,
    out errorType);

您可能应该使用将请求作为参数和 return 您的响应对象的函数,而不是使用 Action,然后您可以利用泛型进行调用,然后处理特定情况。此外,return为结果设置元组或某些通用类型可能是一个好主意,而不是使用输出参数。

public static Tuple<TResponse, ResponseStatus, ResponseErrorType> GetResponse<TRequest, TResponse>(Func<TRequest, TResponse> action, TRequest request)
{
    var status = ResponseStatus.Fail;
    var errorType = ResponseErrorType.None;
    var response = default(TResponse);

    try
    {
        response = action(request);
        status = ResponseStatus.Success;
    }
    catch (CustomException ex)
    {
        errorType = ResponseErrorType.CustomError;
    }
    catch (TimeoutException ex)
    {
        errorType = ResponseErrorType.Timeout;
    }
    catch (Exception ex)
    {
        errorType = ResponseErrorType.GeneralFailure;
    }

    return new Tuple<TResponse, ResponseStatus, ResponseErrorType>(response, status, errorType);
}

我需要在调用签名变化不大的原始方法之前和之后提供功能。

我使用了 Func<..>...

    public static Func<string, string> Hello = name => "hello " + name;

    public static string Hello2(string name) => wrap(Hello)(name);

    // This does NOT retain the name of the arg for hints in the IDE 
    public static Func<string, string> Hello3 = name => wrap(Hello)(name);

    private static Func<string, T> wrap<T>(Func<string, T> orig)
    {
        return name => orig(name.ToUpper());
    }