简体   繁体   中英

Pass a type as parameter to method

I have a class called 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());
    }
}

In the last statement of the getdata() method, the type is passed:

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

I would like to pass the type as parameter to the getdata(RootObject) method.

Is there a way to do this in C# using generics?

The standard way to implement strongly-typed deserialization is this:

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

It looks like you want to read results asynchronously, so you need to actually return the result as Task<T> , as well as to use xxxxAsync versions of methods that read data:

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

You can learn more about generics here: https://msdn.microsoft.com/en-us/library/512aeb7t.aspx

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

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