jeudi 27 août 2015

Getting property values of list of child objects

Let's say I have a Car class with some properties. One of the properties is an IEnumerable of another class, Passenger, with it's own properties.

public class Car
{
   public string Engine { get; set; }
   public int Wheels { get; set; }
   public IEnumerable<Passenger> Passengers { get; set }
}

I am able to get the values of the Engine and Wheels properties (and all others such properties). However, I can't figure out how to get the properties of all the Passenger objects. Here's what I'm doing to get the property values of a Car object:

Type type = car.GetType();
PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
   object carValue = property.GetValue(car, null); 
   Console.WriteLine(carValue.ToString());
}

This obviously doesn't give me the Passenger properties, but outputs something like this instead:

System.Collections.GenericList'1[Passenger]

How do I grab all the property values of every Passenger in the car.Passengers list?





Aucun commentaire:

Enregistrer un commentaire