Ole*_*ers 1 c# reflection list
我尝试将元素添加到通过反射检索的列表中。
下一行
property.PropertyType.GetMethod("Add").Invoke(entity, new[] { innerValue });
Run Code Online (Sandbox Code Playgroud)
抛出错误
对象与目标类型不匹配”(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
Run Code Online (Sandbox Code Playgroud)
entity
是包含上面属性的对象
怎么了
您尝试调用Add
上entitiy
,不在名单上载于entity
“财产。
获取属性的值(应该是列表)并Add
在该引用上调用:
var list = property.GetValue(entity);
property.PropertyType.GetMethod("Add").Invoke(list, new[] { innerValue });
Run Code Online (Sandbox Code Playgroud)