通用Task <object>方法

时间:2019-05-02 08:05:38

标签: c# generics task

我上课要使用我的REST服务。

方法如下:

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
        }
    }

在这种情况下,object就像我自己的带有属性的类(ProjectUser等)。

我的问题是,如何使Task<object>方法成为通用方法,它将采用我想要的某种对象(并将其返回)?

编辑

当我做类似的事情时:

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
        }
    }

我在await repsonse.Contet...上遇到错误:

  

无法将object隐式转换为TObject ...

3 个答案:

答案 0 :(得分:2)

您可以使用通用类型:

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
        }
    }

查看herehere了解更多信息;)

答案 1 :(得分:1)

以下代码将起作用:

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
    }
}

答案 2 :(得分:-1)

使用“ T”类型的占位符代替“对象”。

尝试一下:

  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
     }
  }