【发布时间】:2019-11-25 01:18:31
【问题描述】:
使用反射我可以获得所有数据类型的对象属性和值以及该对象内的对象。但是,如果该对象包含其他对象的列表,我将无法获取列表中的对象。该列表可以包含任何类型的对象。
private static void SaveObj(object obj) {
foreach (var prop in obj.GetType().GetProperties()) {
if (prop.PropertyType.Namespace == "Entities") { //It is an object
object obL = prop.GetValue(obj, null);
SaveObj(obj);
}
else if (prop.PropertyType.Name == "List`1") { //This is a list of objects
object obP = prop.GetValue(obj);
//obP has the list of objects, I can see the list in debug mode.
List<object> obL = (List<object>)prop.GetValue(obj, null);
//This line returns an exception!!
}
else {
columns += prop.Name.ToLower() + ", ";
values[i] = prop.GetValue(obj, null).ToString();
}
... // the code continues ...
}
}
返回的异常信息是:
“无法转换 'System.Collections.Generic.List1[Entities.OrderItem]' to type 'System.Collections.Generic.List1[System.Object]' 类型的对象。”
有趣的是,我可以在 degug 模式下查看所有对象及其内容。在即时窗口中,我可以打印变量 obP 的内容以及列表中的所有对象,但是如何读取它们呢?
关于如何解决这个问题的任何想法?
【问题讨论】:
标签: c# .net reflection