C # Generics and using a non-generic version from a typed method

I am using the RestSharp library to access the REST API.

I want all API requests to go through the same method, so I can add headers, handle errors, and do other things in a central place.

So, I made a method that accepts a generic Func<> and that solves most of my problems, but I don’t know how to handle the case when I don’t have a return type.

 private T PerformApiCall<T>(RestRequest restRequest, Func<RestRequest, IRestResponse<T>> restMethod) { var response = restMethod.Invoke(restRequest); //handle errors .... return response.Data; } 

I call it this way:

 var apples = PerformApiCall(new RestRequest('/api/apples'), req => Client.Execute<List<Apple>>(req)); 

But I ran into a problem, a bunch of API calls have no return type, because they do not return data. So I used Client.Execute(req) , and I got an error saying that type arguments could not be deduced, I tried to pass, but this failed because it could not convert the non-generic IRestResponse to printed.

Any ideas on how to handle this in a good way?

+5
source share
1 answer

One thing you could try is to add an overload to your PerformApiCall function, which accepts Func with a non-generic result type and returns nothing:

 // Notice the `Func` has `IRestResponse`, not `IRestResponse<T>` public void PerformApiCall(RestRequest restRequest, Func<RestRequest, IRestResponse> restMethod) ... 

Then, depending on how complex your error checking / logic is, you can move it to a separate method (which returns the answer) and call it from both PerformApiCall overloads:

 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; 

You received a compiler error because the sound treats the subtype as if it were an instance of its supertype, but it does not sound to do it in the other direction (this is what happened when you changed your call code to all of Client.Execute(req) , returning not generic).

Here's an ideal paste illustrating this: http://ideone.com/T2mQfl

+2
source

Source: https://habr.com/ru/post/1204601/


All Articles