通用函数包装器 [英] Generic Function wrapper

查看:88
本文介绍了通用函数包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多功能不同的内容,但是参数和try catch内部几乎相似.无论如何,有没有要包装的功能,以减少多余的代码.

I have many functions with different content but the parameters and try catch inside is almost similar. Is there anyway to wrap the function up so that can reduce redundant codes.

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传递给您的方法.

You can pass an Action to your method.

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

这篇关于通用函数包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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