[英]How to obtain a list of objects inside another object using reflection
使用反射,我可以获得所有数据类型和该对象内的对象的对象属性和值。 但是如果对象包含其他对象的列表,我在获取列表中的对象时遇到问题。 该列表可以包含任何类型的对象。
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.List 1[Entities.OrderItem]' to type 'System.Collections.Generic.List
的对象转换1[Entities.OrderItem]' to type 'System.Collections.Generic.List
1[System.Object]'。 ”
有趣的是,我可以在调试模式下看到所有对象及其内容。 在立即窗口中,我可以使用列表中的所有对象打印变量 obP 的内容,但如何读取它们?
关于如何解决这个问题的任何想法?
您可以尝试将其转换为IEnumerable
,然后使用.Cast<object>().ToList()
像这样:
IEnumerable obL = prop.GetValue(obj, null) as IEnumerable;
List<object> list = obL.Cast<object>().ToList();
罪过List
实现了ICollection
接口,您可以执行以下操作,而不是尝试将返回值转换为List<object>
:
ICollection collection = (prop.GetValue(obj, null) as ICollection);
if (collection != null)
{
object[] array = new object[collection.Count];
collection.CopyTo(array, 0);
//if you need a list just create a new one and pass in the array: new List<object>(array);
}
作为旁注,您的:
if (prop.PropertyType.Namespace == "Entities")
{
object obL = prop.GetValue(obj, null);
SaveObj(obj);
}
只是导致无限循环,这会导致StackOverflow
/ OutOfMemory
异常,可能想将其更改为SaveObj(obL);
如果这是预期的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.