循环使用类和子类来检索C#中的属性和值

Ric*_*use 2 c# class typeof getproperties

我正在尝试遍历一个类及它的子类来获取与它一起传递的值.

这是我的班级:

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

    public ChildClass1 ChildClass1 { get; set; }
    public ChildClass2 ChildClass2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

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>();
    }
}
Run Code Online (Sandbox Code Playgroud)

两个问题:

  1. 我传递给GetProperties,传递子类,然后循环通过它的属性,如果它是一个类,我该怎么办?
  2. 如果属性项不是类,如何从属性项中获取值?

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

谢谢

Chr*_*air 6

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Hei*_*nzi 5

克里斯已经回答了您问题的第一部分,所以我不再重复。对于第二部分,只要拥有的实例MainClass,就可以使用(恰当命名的)PropertyInfo.GetValue方法

object value = property.GetValue(myInstance, null);
Run Code Online (Sandbox Code Playgroud)

(如果使用.NET 4.5,则可以省略第二个(null)参数。不过,较早的版本需要它。)

最后,您的代码可能如下所示(我无耻地复制和扩展了Chris的版本)(未经测试):

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

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

        object value = property.GetValue(instance, null);
        if (value != null) {
            WriteToLog(value.ToString());
            GetProperties(property.PropertyType, value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果您的任何对象使用索引属性(C#索引器或VB中带有参数的属性),此代码都会失败。在这种情况下,将需要为GetValue提供适当的索引或参数。