首页 / 问答 / C#&.NET应用程序编程开发中如何使用反射递归获取一个类的属性和子属性呢?

C#&.NET应用程序编程开发中如何使用反射递归获取一个类的属性和子属性呢?

.NET C# class 反射 .NET Core 1.72K 次浏览
0

在C#&.NET的应用程序编程开发中,现需要使用反射做类似于递归地获取一个对象的属性和子属性的功能。

以下代码获取到了对象的属性,但代码的问题是:它只获取了第一级类的属性信息,如何使用反射自动获得所有属性(包括属性是类的子属性)?
示例代码如下:

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; } }

测试示例代码如下:

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: System.Collections.Generic.List`1[TreeViewReflectionExample.Address]

期望的结果应该是这样的:

MyBottle:
      BottleName: Big bottle
      BottageAge: 2
Addresses:
      AddressLine1: 1 Main St
      AddressLine2: 2 Main St
      SpecialFolders:
            TemplateFolder: Templates
            UserFolder: UserProfile
回复 [×]
提交评论
请输入评论内容

2 个回答

  • 0

    问题描述的示例代码中有些问题:
    1.条件判断if (property.PropertyType.Assembly == objType.Assembly)会忽略像List<>这个的集合类型的属性
    2.没有对集合类型的值进行特殊处理

    优化后的PrintProperties方法如下:

    Rector的个人主页

    Rector

    2021-11-06 回答

    • 0

      或者作如下方式的修改:

      Rector的个人主页

      Rector

      2021-11-06 回答

      我来回答