mercredi 27 janvier 2016

Pass object at runtime using a string

There is loads of stuff on here about reflection but I can't seem to get my head around my specific problem.

My Classes:

public class Box
{
   public string Name { get; set; }
   public int Size { get; set; }
}

public class Pallet
{
   public Box b1 = new Box();
   public Box b2 = new Box();
}

The Code for Creating the object:

Pallet p = new Pallet();
p.b1.Size = 5;
p.b2.Size = 10;

The code to display the size of a chosen box:

MessageBox.Show(p.b1.Size.ToString());

I would like to select the box at runtime using a string. i.e.

string boxid = "b1";
Object myObj = p. + boxid;          

MessageBox.Show(myObj.Size.ToString());

Obviously this code will not work. What would be the correct way to get the value of the chosen box in this case 5?





Aucun commentaire:

Enregistrer un commentaire