我有一个函数,我想将下面的 Ping 和 Pong 转换为通用类型。是否可以?
private Pong ReadDataFromApi(string url, Ping data)
{
string url = "URL_TO_HIT";
WebResponse response = Util.SendWebRequest<Ping>(url, data, 30000);
var res = new Pong();
if (response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var objText = reader.ReadToEnd();
res = JsonConvert.DeserializeObject<Pong>(objText);
}
}
return res;
}
我可以转换为以下内容:
private T ReadDataFromApi(string url, T data) T : class
{
string url = "URL_TO_HIT";
WebResponse response = Util.SendWebRequest<T>(url, data, 30000);
var res = new Pong();
if (response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var objText = reader.ReadToEnd();
res = JsonConvert.DeserializeObject<Pong>(objText);
}
}
return res;
}
不确定如何接受 Pong 作为通用参数。
最佳答案
这样的事情应该工作:
private TPong ReadDataFromApi<TPing, TPong>(string url, TPing data)
where TPing : class
where TPong : class,new() //You need to create instances of TPong
{
WebResponse response = Util.SendWebRequest<TPing>(url, data, 30000);
var res = new TPong(); //Create instance of TPong
if (response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var objText = reader.ReadToEnd();
res = JsonConvert.DeserializeObject<TPong>(objText);
}
}
return res;
}
关于C# : how to accept two generic parameters,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37348271/