1

我的 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 方法,具体取决于返回类型。一定有聪明的办法!

4

1 回答 1

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)

于 2013-09-13T09:23:09.027 回答