递归获取类的属性和子属性

递归获取类的属性和子属性,第1张

递归获取类的属性和子属性

您的代码有两个问题:

  1. 因为条件的缘故,
    if (property.PropertyType.Assembly == objType.Assembly)
    你会
    System.Collections
    List<>
  2. 您不会对
    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); }        }    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5063968.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存