2017-08-01 86 views
1

傳遞和返回兩個不同的泛型類現在我使用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; 
    } 
} 

我想避免使用條件語句,並在硬編碼傳遞的潛在類型。我只是不知道該如何去這樣做。

回答

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; 
    } 
} 
2

您可以用逗號將它們

public static TResponse SendReceive<TRequest,TResponse>(string sUrl, TRequest sPayload) 
{ 
    .... 
} 
2

分離指定多個泛型類型,您可以添加使用此這樣

多個參數
public static T1 SendReceive<T1,T2,...Tn>(string sUrl, TRequest sPayload) 
{ 
    //TODO Code 
} 

然後你可以這樣稱呼它

className.SendResponse<Class1, Class2,...Classn>(...);