簡體   English   中英

具有不同數量參數的代表

[英]Delegates with varying number of parameters

我編寫了一個 DLL,它調用了我無權訪問的第三方 API。

由於用戶可以退出和重新啟動應用程序的方式,每個方法都有很多圍繞檢查訪問和刷新令牌的邏輯,以便通過 API 進行身份驗證。 (以及錯誤處理處理)這導致每個不同的 API 調用都有大量重復的代碼。

我想重構它,這樣我就可以將我想要的響應對象類型傳遞給一個名為 ExecuteApiCall 的通用方法。 然后可以為特定的 REST 調用調用適當的方法。

我用以下簽名創建了這個方法:

private T ExecuteApiCall<T>(string name, Action<T> requestCall) where T : IApiResponse, new()

這正如我所期望的那樣工作。 我現在遇到的問題是一些請求需要額外的參數,我無法將不同數量的參數傳遞給 Action 委托。

我該如何處理?

我想改成

Action<T, ApiRequestParameters>

其中 ApiRequestParameters 是所有可能參數的類,面向公眾的方法可以在調用私有 ExecuteApiCall 之前設置它需要的參數。 但這並不是真正的最佳實踐。

我真的希望這對某人有意義,並提前致謝。 如果需要,很樂意提供更多的代碼示例。

需要處理以下問題

ExecuteCallA()
{
    //The API call is done here using RestSharp
}

ExecuteCallB(string aParameter)
{
    //The API call is done here using RestSharp
}

ExecuteCallC(string aParameters, int anotherParameter)
{
    //The API call is done here using RestSharp
}

或者將 Action 設置為看起來像這樣會更容易。

Action<T, object, object, object>

這樣它就可以處理額外的參數,而忽略任何它不需要的參數。

編輯:

感謝肖恩的建議,這可能是我會去的。 我的另一個選擇,再次不確定這里的最佳實踐......

將讓公共簽名包含方法參數並將它們設置為私有字段。

private string myParameter;
public ApiResponseA GetWhatever(string a)
{
    myParameter = a;
    ExecuteApiCall<ApiResponseA>();
    myParameter = null;
}

然后將負責實際 API 調用的私有方法更改為使用私有字段而不是參數。 想法?

我會為一定數量的參數添加重載。 例如:

private T ExecuteApiCall<T>(string name, Action<T> requestCall) where T : IApiResponse, new();

private T ExecuteApiCall<P1, T>(string name, P1 p1, Action<P1, T> requestCall) where T : IApiResponse, new()

private T ExecuteApiCall<P1, P2, T>(string name, P1 p1, P2 p2, Action<P1, P2, T> requestCall) where T : IApiResponse, new()

// etc

實現起來有點重復,但是一旦完成,您就可以忘記它,它會使您向用戶公開的 API 更加清晰和可預測。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM