Nullable、Nullable、またはTとしてマークしてみましたか?成功しないと...nullを返すT
このメソッドは抽象クラスの一部であり、あらゆるタイプのオブジェクトを取得して任意の派生クラスから使用できるように、できるだけジェネリックにする必要があります。
public T GetFromApi<T>(string apiRequest, string content)
{
try
{
log.Debug("Requesting '" + apiRequest + "' from API with the following parameters: " + content);
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_httpClient.DefaultRequestHeaders.Add("Authorization", string.Format("{0} {1}", _token.token_type, _token.access_token));
var httpContent = new StringContent(content);
HttpResponseMessage response = _httpClient.GetAsync(apiRequest).Result;
if (response.IsSuccessStatusCode)
{
//Returns requested Object (T) from API
log.Info("Returning requested object " + typeof(T).ToString());
return response.Content.ReadAsAsync<T>().Result;
}
else
{
log.Error("Error accessing API.");
return null;
}
}
catch (Exception ex)
{
log.Fatal("Error accessing API.", ex);
throw ex;
}
}
else文のリターンヌルは私にエラーを与える:渡された型は構造体である場合
Cannot convert null to type parameter 'T'
'default(T)'を返すのはどうですか? –
ところで、元の例外のスタックトレースを保持するには、 'throw ex;'よりも 'throw;'を優先させるべきです。 –
tnks @UweKeim .. that solve ... – Nuno