Descriptor type and children

This code:

foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(lst[0])) { Console.WriteLine(descriptor.Name); } 

will write out the name of all the items in my list. That is, FirstName / LastName or something else. How to write out children of an element? If there was an β€œCars” element on my list that had the type and color of the car, how would I use TypeDescriptor to write it?

What I got at the moment:

  • Firstname
  • Surname
  • Car

I want something like this:

  • Firstname
  • Lastname
  • Car: Toyota, Red
  • Car: Mitsubishi, Green

Does anyone know how to do this?

+4
source share
3 answers

The PropertyDescriptor class provides a method called GetChildProperties(System.Object) .
You should be able to pass a link from your current object to the method and get other collections containing child properties in return.
It may even make sense to inherit from this class in order to get full functionality.

See here for documentation.

+1
source

You will need to check the type of the object, and then get its properties when it is correct.

 foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(lst[0])) { Console.WriteLine(descriptor.Name); if(descriptor.PropertyType == typeof(Car)) { foreach(var child in descriptor.GetChildProperties()) { Console.WriteLine(child.Name); } } } 
+1
source

I think I get it. As long as I have a type in which I need children for (Cars), I can do like this:

  foreach (Car c in lst[0].Cars) { PropertyInfo[] properties = car.GetType().GetProperties(); foreach (PropertyInfo item in properties) { string propertyName = item.Name; } } 
0
source

All Articles