.net - How to reference a field by reflection -
sorry title, it's not explicit.
further precedent question, want subscribe method event object retrieved dynamically (via reflection). object in question field of control :
public void subscribeevents(control control) { type controltype = control.gettype(); fieldinfo[] fields = controltype.getfields(bindingflags.public | bindingflags.nonpublic | bindingflags.instance); methodinfo method = typeof(trace).getmethod("writetrace"); // "button1" hardcoded sample fieldinfo f = controltype.getfield("button1", bindingflags.public | bindingflags.nonpublic | bindingflags.instance); // "click" hardcoded sample eventinfo einfo = f.fieldtype.getevent("click"); if (einfo != null) { eventhandler dummydelegate = (s, e) => writetrace(s, e, einfo.name); delegate realdelegate = delegate.createdelegate(einfo.eventhandlertype, dummydelegate.target, dummydelegate.method); einfo.addeventhandler(?????, realdelegate); // how can reference variable button1 ??? } }
i don't know how reference variable 'button1'. i've tried :
public void subscribeevents(control control) { type controltype = control.gettype(); fieldinfo[] fields = controltype.getfields(bindingflags.public | bindingflags.nonpublic | bindingflags.instance); methodinfo method = typeof(trace).getmethod("writetrace"); // "button1" hardcoded sample fieldinfo f = controltype.getfield("button1", bindingflags.public | bindingflags.nonpublic | bindingflags.instance); // "click" hardcoded sample eventinfo einfo = f.fieldtype.getevent("click"); type t = f.fieldtype; object o = activator.createinstance(t); f.getvalue(o); if (einfo != null) { eventhandler dummydelegate = (s, e) => writetrace(s, e, einfo.name); delegate realdelegate = delegate.createdelegate(einfo.eventhandlertype, dummydelegate.target, dummydelegate.method); einfo.addeventhandler(o, realdelegate); // why can refer variable button1 ??? } }
but have exception here :
f.getvalue(o);
system.argumentexception unhandled message=field 'button1' defined on type 'windowsformsapplication1.form1' not field on target object of type 'system.windows.forms.button'.
that's because you're trying create new instance of button
, trying value of button1
property, not exist.
replace this:
type t = f.fieldtype; object o = activator.createinstance(t); f.getvalue(o);
with this:
object o = f.getvalue(control);
you can use method obtain value of field object:
public static t getfieldvalue<t>(object obj, string fieldname) { if (obj == null) throw new argumentnullexception("obj"); var field = obj.gettype().getfield(fieldname, bindingflags.public | bindingflags.nonpublic | bindingflags.instance); if (field == null) throw new argumentexception("fieldname", "no such field found."); if (!typeof(t).isassignablefrom(field.fieldtype)) throw new invalidoperationexception("field type , requested type not compatible."); return (t)field.getvalue(obj); }
Comments
Post a Comment