您的代码有两个问题:
- 因为条件的缘故,
if (property.PropertyType.Assembly == objType.Assembly)
你会System.Collections
像List<>
- 您不会对
propValue
集合有不同的对待。因此它将打印List
属性,而不是其元素属性。
您可以将其更改为例如:
public void PrintProperties(object obj, int indent){ if (obj == null) return; string indentString = new string(' ', indent); Type objType = obj.GetType(); PropertyInfo[] properties = objType.GetProperties(); foreach (PropertyInfo property in properties) { object propValue = property.GetValue(obj, null); var elems = propValue as IList; if (elems != null) { foreach (var item in elems) { PrintProperties(item, indent + 3); } } else { // This will not cut-off System.Collections because of the first check if (property.PropertyType.Assembly == objType.Assembly) { Console.WriteLine("{0}{1}:", indentString, property.Name); PrintProperties(propValue, indent + 2); } else { Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue); } } }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)