我需要在下面的代碼約束來解決上述編譯器錯誤:捕獲或拋出的類型必須從System.Exception
private T GetResponse<T, TError>(HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<T>().Result;
}
else
{
if (response.StatusCode == HttpStatusCode.BadRequest)
{
var ex = response.Content.ReadAsAsync<TError>().Result;
throw ex;
}
}
throw new NotImplementedException();
}
我打電話上面如下:
public int MyMethod(string param)
{
var response = client.PostAsJsonAsync(url, param).Result;
return GetResponse<int, MyException>(response);
}
MyException
確實派生自System.Exception
,但是我得到了上述編譯器錯誤。是否需要約束?
我也建議你避免使用Task.Result來阻塞線程,而是改用async方法。 –
爲什麼不簡單地嘗試一下呢? – HimBromBeere