现在我正在使用T
用于Generic1,但是当我传入sPayload时可以理解得到错误,因为我不确定如何指定第二种泛型类型。
public static Generic1 SendReceive<Generic1>(string sUrl, Generic2 sPayload)
{
using(WebClient webclient = new WebClient())
{
webclient.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = webclient.UploadString(sUrl, JsonConvert.SerializeObject(sPayload));
Generic1 parsedResponse = JsonConvert.DeserializeObject<Generic1>(response);
return parsedResponse;
}
}
我希望避免使用条件语句并对传入的潜在类型进行硬编码。我只是不确定如何执行此操作。
答案 0 :(得分:3)
您需要在声明中指定两种类型:
public static TResult SendReceive<TResult, TPayLoad>(string sUrl, TPayLoad sPayload)
{
using(WebClient webclient = new WebClient())
{
webclient.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = webclient.UploadString(sUrl, JsonConvert.SerializeObject(sPayload));
TResult parsedResponse = JsonConvert.DeserializeObject<TResult>(response);
return parsedResponse;
}
}
答案 1 :(得分:2)
您可以使用逗号
分隔多个泛型类型public static TResponse SendReceive<TRequest,TResponse>(string sUrl, TRequest sPayload)
{
....
}
答案 2 :(得分:2)
您可以使用这种方式添加多个参数
public static T1 SendReceive<T1,T2,...Tn>(string sUrl, TRequest sPayload)
{
//TODO Code
}
然后你可以这样称呼它
className.SendResponse<Class1, Class2,...Classn>(...);