我的ASP.Net MVC控制器中有以下代码:
public ActionResult GetAnimals()
{
List<Dog> dogs = GetDogs("api/dogs).Result;
List<Cat> dogs = GetCats("api/cats).Result;
List<Horse> dogs = GetCats("api/cats).Result;
...
...
}
private async Task<List<Dog>> GetDogs(string requestUri)
{
String ret = "";
var client = new HttpClient();
client.BaseAddress = new Uri("http://theservice.com/");
var response = client.GetAsync(requestUri).Result;
if (response.IsSuccessStatusCode)
{
ret = await response.Content.ReadAsAsync<List<Dog>>();
}
else
{ }
return ret;
}
private async Task<List<Cat>> GetCats(string requestUri)
{
String ret = "";
var client = new HttpClient();
client.BaseAddress = new Uri("http://theservice.com/");
var response = client.GetAsync(requestUri).Result;
if (response.IsSuccessStatusCode)
{
ret = await response.Content.ReadAsAsync<List<Cat>>();
}
else
{ }
return ret;
}
如何避免一遍又一遍地重写Get方法,具体取决于返回类型。必须有一个聪明的方法!
答案 0 :(得分:3)
使用泛型:
private async Task<List<T>> GetItems<T>(string requestUri)
{
String ret = "";
var client = new HttpClient();
client.BaseAddress = new Uri("http://theservice.com/");
var response = await client.GetAsync(requestUri);
if (response.IsSuccessStatusCode)
{
ret = await response.Content.ReadAsAsync<List<T>>();
}
else
{ }
return ret;
}
您可以在GetDogs
/ GetCats
方法中使用它:
private async Task<List<Dog>> GetDogs(string requestUri)
{
return GetItems<Dog>(requestUri);
}
或直接作为GetItems<ClassName>(requestUri)
。