jeudi 3 mars 2016

Get Property using a string without reflection

The Object Classes...

class Room
    {
        public string Value1 { get; set; }
        public string Value2 { get; set; }
        public string Value3 { get; set; }

        public Room()
        {
            this.Value1 = "one";
            this.Value2 = "two";
            this.Value3 = "three";

        }

    }

    class Building

    {
        public Room Room1 { get; set; }
        public Room Room2 { get; set; }

        public Building()
        {
            this.Room1 = new Room();
            this.Room2 = new Room();
        }

    }

    class Street

    {
        public Building Building1 { get; set; }
        public Building Building2 { get; set; }
        public Building Building3 { get; set; }
        public Building Building4 { get; set; }

        public Street ()
        {
            this.Building1 = new Building();
            this.Building2 = new Building();
            this.Building3 = new Building();
            this.Building4 = new Building();

        }

    }

What I am currently using to get the values...

class go
{
    public void go()
    {
        string SelectedValue = "";
        Street s = new Street();
        string PathToProperty = "s.Building1.Room1.value1";

        if(PathToProperty == "s.Building1.Room1.value1") { SelectedValue = s.Building1.Room1.Value1; }

        if (PathToProperty == "s.Building1.Room1.value2") { SelectedValue = s.Building1.Room1.Value2; }


    }

}

How I would like to get the values... or something similar

string PathToProperty = "s.Building1.Room1.value1";    
SelectedValue = PathToProperty;

The reason being I am making the the PathToProperty by stringing together the text from a bunch of combo boxes. Ultimately I want to avoid having to add to my list of IF statements as the options inside the combo boxes increase.

I have being messing around with reflection but would like to avoid this , I read somewhere you can do this with interfaces (using them to expose properties) but I do not know how.





Aucun commentaire:

Enregistrer un commentaire