首页 > 解决方案 > 如何获取对象的所有属性,包括每个子对象的属性?

问题描述

我试图从一个对象中获取所有属性,包括它的子对象的所有属性,例如:

你有一个A类:

public class A
{
    public Guid Id { get; set; };
    public string Name { get; set; };
    public B BObject { get; set; };
}

然后 B 类可能如下所示:

public class B
{
    public Guid Id { get; set; };
    public string BValue { get; set; };
}

我怎样才能确保当我使用它时PropertyInfo[] properties = a.GetType().GetProperties();,我会在列表中同时获得 A 类和 B 类的所有属性?

标签: asp.net-core

解决方案


你可以结合反射和递归来满足你的需求:</p>

 List<string> properties = new List<string>();
 GetAllProperties<A>(a,properties);

方法:

 public void GetAllProperties<T>(T type, List<string> properties)
    {
        try
        {
            // Get the properties of 'Type' class object.
            PropertyInfo[] myPropertyInfo;
            myPropertyInfo = type.GetType().GetProperties();
            for (int i = 0; i < myPropertyInfo.Length; i++)
            {
                if (!myPropertyInfo[i].PropertyType.Namespace.Contains("System"))
                {
                    object newtype = Activator.CreateInstance(myPropertyInfo[i].PropertyType);
                    GetAllProperties<object>(newtype, properties);
                }
                else
                {
                    properties.Add(myPropertyInfo[i].Name);
                }

            }

        }
        catch(Exception ex)
        {
            throw ex;
        }
    }

推荐阅读