将类型作为参数传递给方法

时间:2015-09-28 17:49:42

标签: c#

我有一个名为RootObject的课程:

public class RootObject
{
    public string Name { get; set; }
    public int Age { get; set; }
    public int Address { get; set; }
}

public void getdata()
{
    WebRequest request = WebRequest.Create("http://addresstojson.com/json.json");
    WebResponse response = await request.GetResponseAsync();

    using (var stream = new StreamReader(response.GetResponseStream()))
    {
       json = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
    }
}

getdata()方法的最后一个语句中,传递了类型:

JsonConvert.DeserializeObject</*here*/>(Stream.ReadToEnd())

我想将类型作为参数传递给getdata(RootObject)方法。

有没有办法在C#中使用泛型?

2 个答案:

答案 0 :(得分:12)

实现强类型反序列化的标准方法是:

public T Get<T>()
{
    string json = ...; // get data somehow
    return JsonConvert.DeserializeObject<T>(json);
}

看起来您想要异步读取结果,因此您需要将结果实际返回为Task<T>,以及使用读取数据的xxxxAsync版本的方法:

public Task<T> GetData<T>()
{
    WebRequest request = WebRequest.Create("http://addresstojson.com/json.json");
    using (WebResponse response = await request.GetResponseAsync())
    {
        using(var stream = new StreamReader(response.GetResponseStream()))
        {
            string json = await stream.ReadToEndAsync();
            T result = JsonConvert.DeserializeObject<T>();
            return result;
        }
    }
}

您可以在此处了解有关泛型的更多信息:https://msdn.microsoft.com/en-us/library/512aeb7t.aspx

答案 1 :(得分:0)

public static async Task<T> GetData<T>(string add)
    {
        WebRequest request = WebRequest.Create(add);
        WebResponse response = await request.GetResponseAsync();

        using (var stream = new StreamReader(response.GetResponseStream()))
        {
            return JsonConvert.DeserializeObject<T>(stream.ReadToEnd());
        }
    }