c# - Load an object with values with reflection -


with code below trying save , load player class , xml document. have write portion working having trouble repopulating player object data stored in playerelement. prefer not use xml serializer classes.

    public class player     {        public string name { get; set; }        public int hitpoint { get; set; }        public int manapoint { get; set; }     }       public player loadplayer(xelement playerelement)     {          player player = new player();          propertyinfo[] properties = typeof(player).getproperties();          foreach (xattribute attribute in playerelement.attributes())         {             propertyinfo property = typeof(player).getproperty(attribute.name.tostring());               if (property != null)             {                   object datavalue = convert.changetype(attribute.value, property.propertytype);                     property.setvalue(player, datavalue);              }         }          return player;     }      public override void write(player value)    {          propertyinfo[] properties = typeof(player).getproperties();          xelement playerelement = new xelement(xmlchildname);          foreach (propertyinfo property in properties)         {             playerelement.add(new xattribute(property.name, property.getvalue(value,   null).tostring()));         }          _doc.root.add(playerelement);          _doc.save(path);     } 

i think need this. reversed traversal attributes, not properties. if there property name of attribute, changed:

propertyinfo[] properties = typeof(player).getproperties();  foreach (xattribute attribute in playerelement.attributes()) {     propertyinfo pi = properties.where(x => x.name == attribute.name).firstordefault();      if (pi != null)     {         pi.setvalue(player, attribute.value);     } } 

Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -