Nun*_*uno 3 c# nullable return-type
我在这个泛型类型T上返回null时遇到了麻烦.我试过将它标记为Nullable,Nullable或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;
}
}
Run Code Online (Sandbox Code Playgroud)
else语句的返回null给出了错误:
无法将null转换为类型参数'T'
T如果传入的类型是结构,则Null可能不是可行的值.
您可以改为返回T引用类型为null 的默认类型:
else
{
log.Error("Error accessing API.");
return default(T);
}
Run Code Online (Sandbox Code Playgroud)
如下面的注释中所述,如果限制T为,则可以返回null class.
public T GetFromApi<T>(string apiRequest, string content) where T : class
...
else
{
log.Error("Error accessing API.");
return null;
}
Run Code Online (Sandbox Code Playgroud)
但是,在您需要检索原始类型(bool,int等)的情况下,您将无法再使用此方法.