jeudi 12 mai 2016

Get Values through reflection C#

I have following code.

Classes:

public class AlloyDock
{
    public int Left { get; set; }
    public int Right { get; set; }
}

public class Charger
{
    public int Left { get; set; }
    public int Right { get; set; }
}
public class VehicleControlTest
{
    public Charger Charger1 { get; set; }
}
public class BasicControlTest
{
    public AlloyDock AlloyDock1 { get; set; }
}
class Appointment
{
    public BasicControlTest BasicControlTest1 { get; set; }
    public VehicleControlTest VehicleControlTest1 { get; set; }
}

Main Function:

        var obj = new Appointment();
        obj.BasicControlTest1 = new BasicControlTest();
        obj.BasicControlTest1.AlloyDock1 = new AlloyDock();
        obj.BasicControlTest1.AlloyDock1.Left = 1;
        obj.BasicControlTest1.AlloyDock1.Right = 2;

        obj.VehicleControlTest1 = new VehicleControlTest();
        obj.VehicleControlTest1.Charger1 = new Charger();
        obj.VehicleControlTest1.Charger1.Left = 3;
        obj.VehicleControlTest1.Charger1.Right = 4;


        var parentProperties = obj.GetType().GetProperties();
        foreach (var prop in parentProperties)
        {
            // Get Main objects inside each test type.
            var mainObjectsProperties = prop.PropertyType.GetProperties();
            foreach (var property in mainObjectsProperties)
            {
                var leafProperties = property.PropertyType.GetProperties();
                foreach (var leafProperty in leafProperties)
                {
                    Console.WriteLine("{0}={1}", leafProperty.Name, leafProperty.GetValue(obj, null));
                }
            }
        }

I want to get property name and value of leaf node. I am able to get name but when I try to get value (1,2,3,4 respectively). I am getting below error.

Object does not match target type.

I am just banging my head to solve this problem. Can anybody help me with that.





Aucun commentaire:

Enregistrer un commentaire