简体   繁体   中英

Passing and returning two different generic classes in method

Right now I am using T for Generic1, but understandably getting an error when I pass in the sPayload because I'm unsure how to specify a second generic type.

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

I'd like to avoid using conditional statements and hardcoding the potential types being passed in. I'm just unsure how to go about doing this.

You need to specify both types in the declaration:

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

You can specify multiple generic types by separating them with a comma

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

You can add multiple parameters using this this way

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

and then you can call it like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM