[英]C# Generics and using the non-generic version from typed method
我正在使用RestSharp庫來訪問REST API。
我希望所有API請求都通過相同的方法,因此我可以添加標頭,處理錯誤並在中心位置執行其他操作。
所以我創建了一個接受泛型Func<>
的方法,它解決了我的大部分問題,但我不知道如何處理我沒有返回類型的情況。
private T PerformApiCall<T>(RestRequest restRequest, Func<RestRequest, IRestResponse<T>> restMethod)
{
var response = restMethod.Invoke(restRequest);
//handle errors
....
return response.Data;
}
我稱之為:
var apples = PerformApiCall(new RestRequest('/api/apples'), req => Client.Execute<List<Apple>>(req));
但是我遇到了一個問題,一堆API調用沒有返回類型,因為它們不返回數據。 所以我使用Client.Execute(req)
並且我得到錯誤,說明無法推斷類型參數,我試圖通過,但是失敗了因為它無法將非泛型IRestResponse
轉換為鍵入的類型。
關於如何以一種好的方式解決這個問題的任何想法?
您可以嘗試的一件事是向PerformApiCall
函數添加一個重載,該函數采用具有非泛型結果類型的Func
,並且不返回任何內容:
// Notice the `Func` has `IRestResponse`, not `IRestResponse<T>`
public void PerformApiCall(RestRequest restRequest,
Func<RestRequest, IRestResponse> restMethod)
...
然后,根據您的錯誤檢查/邏輯的復雜程度,您可以將其移出到單獨的方法(返回響應),並從PerformApiCall
兩個重載中調用它:
private T PerformRequestWithChecks<T>(RestRequest restRequest,
Func<RestRequest, T> restMethod)
where T : IRestResponse
{
var response = restMethod.Invoke(restRequest);
// Handle errors...
return response;
}
// You can use it from both versions of `PerformApiCall` like so:
//
// // From non-generic version
// var response =
// PerformRequestWithChecks<IRestResponse>(restRequest, restMethod);
//
// // From generic version
// var response =
// PerformRequestWithChecks<IRestResponse<T>>(restRequest, restMethod);
// return response.Data;
您收到編譯器錯誤,因為將子類型視為其超類型的實例是合理的,但是在另一個方向上執行此操作並不合適 (這是將您的調用代碼更改為剛剛發生的情況) Client.Execute(req)
,返回非泛型)。
這是一個ideone粘貼,說明了這一點: http ://ideone.com/T2mQfl
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.