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
Post a Comment