使用泛型

时间:2018-11-19 13:34:38

标签: c# generics

我正在尝试使用反射来动态设置类成员的属性

这是我的课程,我正在尝试动态设置列表,即ResponseBody

public class Response<T>  where T : RealmObject
{
    public string errorMessage { get; set; }
    public string status { get; set; }

    public string totalPages {get;set;}


    public IList<T> ResponseBody { get; set; }
}

以下是服务器尝试在ResponseBody中映射它的响应

{
  "errorMessage": "",
  "status": "Ok",
  "totalPages": 1,
  "contactsList": [
    {
      "firstName": "Ronald",
      "lastName": "Brownn"
    },
    {

      "firstName": "Elvis",
      "lastName": "Presley"
    }
  ]
}

为了将contactsList内的ResponseBody映射到JsonConverter,我编写了以下代码

以下代码将动态创建Response<Contact>,将entityType视为Contact

var responseObj = typeof(Response<>).MakeGenericType(new[] { entityType });
var response = Activator.CreateInstance(responseObj);

以下代码将动态创建对象IList<Contact>

var responseDataList = typeof(List<>).MakeGenericType(new[] { entityType });
var responseList = Activator.CreateInstance(responseDataList);
var responseEntityList =  jArray.ToObject(responseDataList);

现在我想将IList<Contact>分配给Response<Contact>的{​​{1}}成员,我真的不知道该怎么做

2 个答案:

答案 0 :(得分:2)

您需要从类定义中获取PropertyInfo对象:

var responseBodyProperty = responseObj.getProperty("ResponseBody");

然后您可以使用它来设置对象的值:

responseBodyProperty.setValue(response, responseList);

在这一点上,我认为涉及泛型并不重要。您已经在类型创建中介绍了这一点。

答案 1 :(得分:2)

我认为这里不需要反思-反序列化应该能够很好地处理列表。

我还发现了为什么您可能看不到预期的结果; JSON中有contactsList,而C#POCO中有ResponseBody。那就是为什么!

这是一个有效的版本:

响应类别

public class Response<T> where T : class
{
    public string errorMessage { get; set; }
    public string status { get; set; }

    public string totalPages { get; set; }


    public IList<T> ResponseBody { get; set; }
}

使用了JSON

{
    "errorMessage": "",
    "status": "Ok",
    "totalPages": 1,
    "ResponseBody": [  <-- notice I changed this
        {
            "firstName": "Ronald",
            "lastName": "Brownn"
        },
        {

            "firstName": "Elvis",
            "lastName": "Presley"
        }
    ]
}

实际代码:

class Program
{
    //Here I'm loading in your json for testing.
    static string input = File.ReadAllText("Input.json");

    static void Main(string[] args)
    {
        Type genericResponseType = typeof(Response<>).MakeGenericType(new[] { typeof(Person) });
        var result = JsonConvert.DeserializeObject(input, genericResponseType);

        Console.WriteLine(result);

        Console.ReadKey();
    }
}

人员班级:

public class Person
{
    public string firstName { get; set; }
    public string lastName { get; set; }
}