通过方法
问题描述:
传递和返回两个不同的泛型类现在我使用Generic1的T
,但可以理解,当我传入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;
}
}
我想避免使用条件语句,并在硬编码传递的潜在类型。我只是不知道该如何去这样做。
答
您需要在声明指定两种类型:
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;
}
}
答
您可以用逗号将它们
public static TResponse SendReceive<TRequest,TResponse>(string sUrl, TRequest sPayload)
{
....
}
答
分离指定多个泛型类型,您可以添加使用此这样
多个参数public static T1 SendReceive<T1,T2,...Tn>(string sUrl, TRequest sPayload)
{
//TODO Code
}
然后你可以这样称呼它
className.SendResponse<Class1, Class2,...Classn>(...);