[英]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". 我具有解析json响应的通用方法,但是当我尝试在我的方法中调用它时,出现错误“ Type TOut必须是引用类型,才能将其用作方法的通用类型中的参数T ”。 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
). 您的
TryParse<T>
方法说T
必须是一个类( where T : class
)。 Your GetAsync<TOut>
method lets T
be anything - there's no restriction on it. 您的
GetAsync<TOut>
方法允许T
为任意值-对此没有限制。
However, TOut
is used as T
when calling TryParse
. 但是,在调用
TryParse
时,将TOut
用作T
Here's the problem - TOut
can be anything, but T
can only be a class. 这就是问题
TOut
可以是任何东西,但是T
只能是一个类。
Either remove the where T : class
restriction from TryParse
, or add it to GetAsync
( where TOut : class
). 从
TryParse
删除where T : class
限制,或将其添加到GetAsync
( where TOut : class
)。 Which you do depends on your requirements. 您要做什么取决于您的要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.