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

 缺氧 发布于 2023-02-11 10:42

我正在做一些像递归获取对象的属性和子属性的东西 ,但我想以递归方式使用反射来获取每个属性.我从递归打印属性中获取代码.

代码的问题是:它只降低了一级,我想知道如何使用反射自动获取所有属性?我刚刚编写了以下示例Container代码:

public class Container
{
    public Bottle MyBottle { get; set; }
    public List
Addresses { get; set; } public Container() { Address a = new Address(); a.AddressLine1 = "1 Main St"; a.AddressLine2 = "2 Main St"; Addresses = new List
(); Addresses.Add(a); MyBottle = new Bottle(); MyBottle.BottleName = "Big bottle"; MyBottle.BottageAge = 2; } } public class Bottle { public string BottleName { get; set; } public int BottageAge { get; set; } } public class Address { public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public List SpecialFolders { get; set; } public Address() { SpecialFolders = new List(); SpecialFolder sf = new SpecialFolder(); sf.TemplateFolder = Environment.SpecialFolder.Templates.ToString(); sf.UserFolder = Environment.SpecialFolder.UserProfile.ToString(); SpecialFolders.Add(sf); } } public class SpecialFolder { public string TemplateFolder { get; set; } public string UserFolder { get; set; } }

在Main方法中:

static void Main(string[] args)
{
    Container c = new Container();
    PrintProperties(c);
}
public static void PrintProperties(object obj)
{
    PrintProperties(obj, 0);
}
public static 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);
        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);
        }
    }
}

我希望得到:

MyBottle:
      BottleName: Big bottle
      BottageAge: 2
Addresses:
      AddressLine1: 1 Main St
      AddressLine2: 2 Main St
      SpecialFolders:
            TemplateFolder: Templates
            UserFolder: UserProfile

我现在得到的结果:

MyBottle:
  BottleName: Big bottle
  BottageAge: 2
Addresses: System.Collections.Generic.List`1[TreeViewReflectionExample.Address]

有人可以帮我使用PrintProperties方法吗?非常感谢你.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有