简体   繁体   中英

The Type TOut must be a reference type in order to use it as a parameter T in the generic type of method

I have the generic method to parse the json response but when I tries to call it in my method I'm getting an error " The Type TOut must be a reference type in order to use it as a parameter T in the generic type of method". Please help and Let me know how to call the generic method.

private static T TryParse<T>(string input, T defaultVal = default(T)) where T : class
    {
        try
        {
            var result = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(input);
            return result;
        }
        catch (Exception)
        {
            return defaultVal;
        }
    }

public async Task<Tuple<bool, string, TOut>> GetAsync<TOut>(
        Func<string, bool> successTest = null,
        Dictionary<string, string> parameters = null)
    {
        var result = await GetAsync(parameters);
        var response = await GetResponseContentAsync(result.Content);
        var responseObj = TryParse<TOut>(response);


        return Tuple.Create(true, response, responseObj);
    }

Your TryParse<T> method says that T must be a class ( where T : class ). Your GetAsync<TOut> method lets T be anything - there's no restriction on it.

However, TOut is used as T when calling TryParse . Here's the problem - TOut can be anything, but T can only be a class.

Either remove the where T : class restriction from TryParse , or add it to GetAsync ( where TOut : class ). Which you do depends on your requirements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM