gpt4 book ai didi

c# - 在方法中传递和返回两个不同的泛型类

转载 作者:太空宇宙 更新时间:2023-11-03 18:22:54 26 4
gpt4 key购买 nike

现在我正在为 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;
}
}

关于c# - 在方法中传递和返回两个不同的泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45442625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com