dimanche 13 septembre 2015

C#: Parse different classes as object and display property values the same way

I have a couple of classes in c# console application.

public class Cars:List<Car>
{}

and:

public class Drivers:List<Driver>
{}

The goal is to render console-output always the same manner, doesn't matter if cars or drivers are parsed to rendering-method. So the parameter is of type object. Of course the properties may have different names.

The output should look like this:

// Cars
Brand HP  Topspeed
VW    100 200
VW    90  150

or

// Drivers
Name Age Sex 
Pit  18  m
Jane 20  f

So I need to read property-names to make them column headers and then read values for each object. I've already searched a while and always come things like this:

public static void RenderOutput(object obj)
{
    foreach (var prop in obj.GetType().GetProperties())
    {
    }
}

Although at runtime mouseover obj shows all the desired objects and properties (Brand, HP, VW, 100, ...) very well, I do not manage to squeeze the values out of prop item car by car or driver by driver.

Any suggestion? Thx jimbo2015





Aucun commentaire:

Enregistrer un commentaire