2017-08-08 32 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 });