C#:如何接受两个通用参数

时间:2016-05-20 13:42:13

标签: c# generics

我有一个函数,我想将下面的Ping和Pong转换为泛型类型。有可能吗?

private Pong ReadDataFromApi(string url, Ping data)
{
    string url = "URL_TO_HIT";

    WebResponse response = Util.SendWebRequest<Ping>(url, data, 30000);

    var res = new Pong();
    if (response != null)
    {
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            var objText = reader.ReadToEnd();
            res = JsonConvert.DeserializeObject<Pong>(objText);
        }
    }
    return res;
}

我可以转换成以下内容:

private T ReadDataFromApi(string url, T data)  T : class
{
    string url = "URL_TO_HIT";

    WebResponse response = Util.SendWebRequest<T>(url, data, 30000);

    var res = new Pong();
    if (response != null)
    {
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            var objText = reader.ReadToEnd();
            res = JsonConvert.DeserializeObject<Pong>(objText);
        }
    }
    return res;
}

不确定如何接受Pong作为通用参数。

5 个答案:

答案 0 :(得分:7)

这样的事情应该有效:

private TPong ReadDataFromApi<TPing, TPong>(string url, TPing data)
    where TPing : class
    where TPong : class,new() //You need to create instances of TPong
{
    WebResponse response = Util.SendWebRequest<TPing>(url, data, 30000);

    var res = new TPong(); //Create instance of TPong
    if (response != null)
    {
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            var objText = reader.ReadToEnd();
            res = JsonConvert.DeserializeObject<TPong>(objText);
        }
    }

    return res;
}

答案 1 :(得分:1)

你可以像这样使用它

private TPong ReadDataFromApi<TPing,TPong>(string url, TPing data) 
        where TPing : class 
        where TPong : class, new()

答案 2 :(得分:1)

将您的方法更改为:

private TPong ReadDataFromApi<TPong, TPing>(string url, TPing data)  TPong : class, new() where TPing : class
{
    string url = "URL_TO_HIT";
    WebResponse response = Util.SendWebRequest<TPing>(url, data, 30000);

    var res = new TPong(); // USE TPong HERE
    if (response != null)
    {
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            var objText = reader.ReadToEnd();
            res = JsonConvert.DeserializeObject<TPong>(objText); // AND HERE
        }
    }
    return res;
}

使用new()约束,您可以确保TPong具有默认构造函数。您需要这样才能res = new TPong();

并将通用参数TPong传递给DeserializeObject<TPong>

答案 3 :(得分:0)

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

var fooObj = foo<Ping,Pong>(url, data);

see MSDN

答案 4 :(得分:0)

您的签名应该是这样的:

private T ReadDataFromApi<S,T>(string url, S data) where S : class where T : class

然后调用它等同于你的原始函数将是这样的:

var myPong = ReadDataFromApi<Ping,Pong>(url, data);

您的签名与Func<T, TResult>的签名类似,例如