问题
I have class to consuming my REST service.
Method for this will look like this:
public async Task<object> Get(string controller)
{
object data;
HttpResponseMessage response = await this.HttpClient.GetAsync(UrlService.BuildEndpoint(controller));
if (response.IsSuccessStatusCode)
{
data = await response.Content.ReadAsAsync<object>();
return data;
}
else
{
throw new Exception(); //todo
}
}
in this case, object can be like my own class (Project, User etc) with propertys.
My question is, how to make Task<object> methods to be generic, that will take kind of objects that i want to (and return it)?
EDIT
When i do something like:
public async Task<TObject> Get<TObject>(string controller)
{
TObject data;
HttpResponseMessage response = await this.HttpClient.GetAsync(UrlService.BuildEndpoint(controller));
if (response.IsSuccessStatusCode)
{
data = await response.Content.ReadAsAsync<object>();
return data;
}
else
{
throw new Exception(); //todo
}
}
i get an error on await repsonse.Contet...:
Cannot implicity convert
objecttoTObject...
回答1:
You can use generic types:
public async Task<TObject> Get<TObject>(string controller)
{
TObject data;
HttpResponseMessage response = await this.HttpClient.GetAsync(UrlService.BuildEndpoint(controller));
if (response.IsSuccessStatusCode)
{
data = await response.Content.ReadAsAsync<TObject>();
return data;
}
else
{
throw new Exception(); //todo
}
}
Have a look here and here for more infos ;)
回答2:
The following code would work:
public async Task<TObject> Get<TObject>(string controller)
{
HttpResponseMessage response = await this.HttpClient.GetAsync(UrlService.BuildEndpoint(controller));
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsAsync<TObject>();
}
else
{
throw new Exception(); //todo
}
}
回答3:
Instead of "object" use a "T" type placeholder.
Try this:
public async Task<T> Get (string controller)
{
T data;
HttpResponseMessage response = await this.HttpClient.GetAsync (UrlService.BuildEndpoint (controller));
if (response.IsSuccessStatusCode)
{
data = await response.Content.ReadAsAsync<T> ();
return data;
}
else
{
throw new Exception (); //todo
}
}
来源:https://stackoverflow.com/questions/55948085/generic-taskobject-method