小编Nun*_*uno的帖子

返回null T

我在这个泛型类型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)

c# nullable return-type

3
推荐指数
1
解决办法
579
查看次数

标签 统计

c# ×1

nullable ×1

return-type ×1