2017-01-23 191 views
2

我有許多不同內容的函數,但參數和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; 
} 

回答

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

是否有可能訪問action1()和action2()內部的值? –

+0

@Amigo你爲什麼需要它?例如,如果你需要傳遞參數,你可以使用類型化的Action:'Action ',你可以像這樣設置:'(myInt)=> doSomething(myInt)'並且像這樣使用它:'action1(213 );';我邀請你,如果你不知道他們已經搜索了'C#lambdas'來理解它是如何工作的。 – Kilazur

1

不使用動作,你也許應該使用,將採取請求的參數和返回的響應對象的功能,那麼你可以採取仿製藥的好處,使該調用然後處理特定情況。同樣返回元組或Result的某個泛型類型可能是一個好主意,而不是使用out參數。

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