c# - Pass object at runtime using a string -


there loads of stuff on here reflection can't seem head around 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 creating object:

pallet p = new pallet(); p.b1.size = 5; p.b2.size = 10; 

the code display size of chosen box:

messagebox.show(p.b1.size.tostring()); 

i select box @ runtime using string. i.e.

string boxid = "b1"; object myobj = p. + boxid;            messagebox.show(myobj.size.tostring()); 

obviously code not work. correct way value of chosen box in case 5?

since b1 , b2 fields, can them using getfield. on fieldinfo, call getvalue providing instance of pallet specific field for.

box box = (box)typeof(pallet).getfield(boxid).getvalue(pallet); 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -