C#: use reflection to obtain reference to instance's member in constructor -
given class
public class myclass { public someobject myobject; public anotherobject myotherobject; // many more members public myclass() { string name = getmembernameandvalue(); // name == "myobject" or "myotherobject" // obtain reference _this_ instance's // fellow member given `name` can set member's value. } }
i don't want obtain new object same type given name
, want actual reference fellow member of instance beingness created can set own member's value.
edit: changed name of get
function. is, (server call) function not retrieves name of fellow member set, value set to. fellow member (i.e. myobject
or myotherobject
) set not fixed, , 1 may not set @ all.
edit2: reason intend(ed) utilize reflection list of fellow member objects big , wanted avoid using many if
statements or long switch
(as recommended in comments below).
based off of msdn entry fieldinfo.setvalue
(msdn):
get appropriate fieldinfo
object:
fieldinfo myfieldinfo = mytype.getfield(name, bindingflags.nonpublic | bindingflags.instance);
set value:
myfieldinfo.setvalue(this, new someobject());
as reflection, not efficient; , there lots of places assign wrong type, etc. careful when doing this. without seeing more code, unlikely actually want utilize reflection here.
c# reflection
No comments:
Post a Comment