c# - Deferred type inference for inherited class method -
what i'm trying do, without success, method on base class that, using reflection, update properties defined inherited classes. so, starting specific method this
/** fill item xml node */ public tblitem fromxml (xmlnode itemnode) { foreach (xmlnode itemfield in itemnode) { type mytype = this.gettype (); propertyinfo mypropinfo = mytype.getproperty (itemfield.name); if (mypropinfo != null) { mypropinfo.setvalue (this, convert.changetype (itemfield.innertext, mypropinfo.propertytype), null); } else { throw new missingfieldexception (string.format ("[fieldname]wrong fieldname: {0}", itemfield.name)); } } return this; }
i need defined in base class called i.e. tblbase, containing no properties @ all, , being used seamlessly in derived classes, i.e. tblderived1: tblbase etc. in there different properties defined each of them, i'm here asking: there way or dream of dirty mind? btw, how need use stuff:
xmldoc.load (xmldbpath); xmlnodelist itemnodes = xmldoc.selectnodes (nodes2select); //tblitem inherits tblbase tblitem ti = new tblitem (); foreach (xmlnode itemnode in itemnodes) { print (((tblitem)ti).fromxml (itemnode).tostring ()); }
see code using generics below, replaced xml node name , value test.
public t fromxml<t>(string name, string value) t: tblbase { type mytype = this.gettype(); propertyinfo mypropinfo = mytype.getproperty(name); if (mypropinfo != null) { mypropinfo.setvalue(this, convert.changetype(value, mypropinfo.propertytype), null); } else { throw new missingfieldexception(string.format("[fieldname]wrong fieldname: {0}", name)); } return (t)this; }
and calling it: var result = youritem.fromxml(somename, somevalue);
but, work without generics well:
public tblbase fromxml (xmlnode itemnode) { foreach (xmlnode itemfield in itemnode) { type mytype = this.gettype (); propertyinfo mypropinfo = mytype.getproperty (itemfield.name); if (mypropinfo != null) { mypropinfo.setvalue (this, convert.changetype (itemfield.innertext, mypropinfo.propertytype), null); } else { throw new missingfieldexception (string.format ("[fieldname]wrong fieldname: {0}", itemfield.name)); } } return this; }
and calling it: tblitem result = (tblitem)youritem.fromxml(...);
edit:
this work on properties (with , set). if have field data members want change in same way, need use getfield instead of getproperty:
var myfieldinfo = mytype.getfield(name) ... myfieldinfo.setvalue (this, convert.changetype (itemfield.innertext, myfieldinfo.fieldtype));
Comments
Post a Comment