2017-08-08 53 views
1

我尝试将元素添加到通过反射检索的列表中。通过反射向列表中添加元素

下面一行

property.PropertyType.GetMethod("Add").Invoke(entity, new[] { innerValue }); 

抛出一个错误

对象不匹配目标类型”(Reflection.TargetException)

但类型应该比赛:

string listType=property.PropertyType().FullName; // System.Collections.Generic.List`1[[My.Entities.Task, My.Entities, Version=1.4.6429.20475, Culture=neutral, PublicKeyToken=null]] 
string elementType=innerValue.GetType().FullName; // My.Entities.Task 

entity是包含上述

的属性的对象有什么不对吗?

回答

4

您尝试调用Addentitiy,而不是在entity的财产中包含的清单。

获取财产的(这应该是列表),并在该参考调用Add

var list = property.GetValue(entity); 
property.PropertyType.GetMethod("Add").Invoke(list, new[] { innerValue });