通用函数包装器

时间:2017-01-23 09:02:49

标签: c# methods 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;
}

3 个答案:

答案 0 :(得分:6)

您可以将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);

答案 1 :(得分:0)

使用Action应该使用一个将请求作为参数并返回响应对象的函数,然后您可以利用泛型来进行调用,然后处理特定情况。同样为结果返回元组或一些泛型类型可能是一个好主意,而不是使用输出参数。

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

答案 2 :(得分:0)

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

我用过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());
    }