简体   繁体   English

获取要在通用参数中使用的类的类型

[英]Get the type of class to use in generic parameter

I am trying to make a method that accepts any model to be bound to a Json response but I can't work out how to dynamically insert the type of class model into the generic parameter. 我正在尝试制作一种方法,该方法接受任何要绑定到Json响应的模型,但无法解决如何将类模型的类型动态插入到通用参数中的问题。

This is what I've got so far: 到目前为止,这是我得到的:

    public static async Task<object> DoPost(string url, FormUrlEncodedContent formEnc, object model)
    {
        using (HttpClient client = new HttpClient())
        using (HttpResponseMessage response = await client.PostAsync(url, formEnc))
        using (HttpContent content = response.Content)
        {
            var result = await content.ReadAsStringAsync();
            var modelType = model.GetType();
            model = JsonConvert.DeserializeObject<modelType>(result);

            return model;
        }
    } 

How do I get the proper representation of type into modelType ? 如何将类型的正确表示形式转换为modelType

You can just use JsonConvert.PopulateObject to populate the instance directly : 您可以使用JsonConvert.PopulateObject直接填充实例:

var result = await content.ReadAsStringAsync();
model = JsonConvert.PopulateObject(result, model);

return model;

This can be simply changed to a Generic such as below. 可以简单地将其更改为通用,例如以下。 Then your Generic can be easily deserialized out. 这样,您的泛型就可以轻松地反序列化了。

public static async Task<T> DoPost<T>(string url, FormUrlEncodedContent formEnc)
{
    using (HttpClient client = new HttpClient())
    using (HttpResponseMessage response = await client.PostAsync(url, formEnc))
    using (HttpContent content = response.Content)
    {
        var result = await content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<T>(result);
    }
}

Now this can be called with any type of model as the generic parameter. 现在可以使用任何类型的model作为通用参数来调用它。 This can be called now just passing in the Generic paramter as T such as: 现在可以将其传递给T例如:

 var user = DoPost<User>(url, formEnc);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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