asp.net-core - 如何获取对象的所有属性,包括每个子对象的属性?
问题描述
我试图从一个对象中获取所有属性,包括它的子对象的所有属性,例如:
你有一个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 类的所有属性?
解决方案
你可以结合反射和递归来满足你的需求:</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;
}
}
推荐阅读
- css - CSS过渡不适用于标签
- javascript - Java 脚本图像更改
- html - 需要输入单选按钮 - 仅设置星号而不是单选按钮
- apache-spark - 从蜂巢与镶木地板读取时火花的性能
- ssl - SSL 证书和私钥不匹配,但 CSR 和私钥匹配?
- ibm-cloud - IBM Watson Assistant 中的数字比较
- angular - Symfony 4 身份验证和 CORS
- javascript - 为什么我的 javascript 一直引用相同的 innerHTML?
- javascript - discord.js 函数是异步的,但它给了我:await must be in async function error in the console
- postgresql - 如何在 K8s 集群内备份更新 Postgres 数据库