c# - Get and set the field value by passing name -


i have field in class random name like:

class foo {     public string a2de = "e2" } 

i have name of field in variable like:

string vari = "a2de" 

can or set value of field a2de using value of vari?

like:

getvar(vari) 

or

setvar(vari) = "e3" 

you have use reflection.

to value of property on targetobject:

var value = targetobject.gettype().getproperty(vari).getvalue(targetobject, null); 

to value of field it's similar:

var value = targetobject.gettype().getfield(vari).getvalue(targetobject, null); 

if property/field not public or has been inherited base class, need provide explicit bindingflags getproperty or getfield.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -