I'm trying to loop through a class and it's child classes to get the values passed with it.
Here's my class:
public class MainClass
{
bool IncludeAdvanced { get; set; }
public ChildClass1 ChildClass1 { get; set; }
public ChildClass2 ChildClass2 { get; set; }
}
Here's my code so far
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>();
}
}
Two questions:
Hopefully this all makes sense. If not, don't hesitate to ask and I'll try and clarify.
Thanks
You can easily rewrite it to be recursive without generics:
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);
}
}
Not sure on your second question "how do I get the value from the property item if it isn't a class" (I'll edit/update when we figure that out)