gpt4 book ai didi

c# - 遍历类和子类以在 C# 中检索属性和值

转载 作者:行者123 更新时间:2023-11-30 19:10:40 25 4
gpt4 key购买 nike

我正在尝试遍历一个类及其子类以获取随它传递的值。

这是我的类(class):

public class MainClass
{
bool IncludeAdvanced { get; set; }

public ChildClass1 ChildClass1 { get; set; }
public ChildClass2 ChildClass2 { get; set; }
}

到目前为止,这是我的代码

GetProperties<MainClass>();

private void GetProperties<T>()
{
Type classType = typeof(T);
foreach (PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
WriteToLog(property.Name + ": " + property.PropertyType + ": " + property.MemberType);
GetProperties<property>();
}
}

两个问题:

  1. 我应该向 GetProperties 传递什么来传递子类,如果它是一个类,然后循环遍历它的属性?
  2. 如果不是类,如何从属性项中获取值?

希望这一切都有意义。如果没有,请不要犹豫,我会尽力澄清。

谢谢

最佳答案

您可以轻松地将其重写为无需泛型的递归:

private void GetProperties<T>()
{
GetProperties(typeof(T));
}

private void GetProperties(Type classType)
{
foreach (PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
WriteToLog(property.Name + ": " + property.PropertyType + ": " + property.MemberType);
GetProperties(property.PropertyType);
}
}

不确定你的第二个问题“如果它不是一个类,我如何从属性项中获取值”(当我们弄清楚时我会编辑/更新)

关于c# - 遍历类和子类以在 C# 中检索属性和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16317290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com