c# - Change the values of members of a list without changing object reference -
i'm working on game, , @ core of game random weapon generation system. basically, works loading bunch of .xml files each own "parttype" tag out of around 20 or (things blade, grip, pommel, etc.).
anyways, have class called weaponpart has properties weight, identifier, etc. have public abstract class weapon
public list<weaponpart> parts
. there then:
public class sword : weapon { public weaponpart blade, pommel, grip, guard; public sword() : base() { pommel = new weaponpart(weaponpart.pommel); //there weaponparttype enum grip = new weaponpart(weaponpart.grip); guard = new weaponpart(weaponpart.guard); blade = new weaponpart(weaponpart.blade); parts.add(pommel); parts.add(grip); parts.add(guard); parts.add(blade); } }
i run method creates new instance of weapon part every file present in folder of xml files. game generates new weaponparts them. now, problem is: when run parts through bunch of foreach loops see parts compatible parts needed weapon.
let's i'm looking pommel sword , i've narrowed down 1 xml file (from here called testpommel
).
if do
weapon.parts[i] = testpommel.clone();
(assuming i
here equal 0 , have made clone()
method deep copies part), properties of pommel
item in parts
list changes, pommel weaponpart
apart of instance of sword class created earlier not. sits there, values @ null.
i assume causing fact changing reference of item in parts
new instance of part, thereby detaching sword.pommel
. there way me copy member values of testpommel
without changing reference of parts[0]
it? appreciated.
edit :
tl;dr: changing value of object in list detaches object reference attached to.
edit :
here's clone() method:
public weaponpart clone() { public weaponpart clone() { weaponpart clone = partfromtype(this.parttype); clone.document = this.document; clone.assignweaponpartdatafromxdocument(); return clone; } }
where document
xdocument associated weaponpart
.
i seem have solved using type.getfield(string name)
method.
public class weaponpart { public void shallowclone(weaponpart parttomodify) { foreach (var field in this.gettype().getfields()) { var parttomodifyfield = parttomodify.gettype().getfield(field.name); if (parttomodifyfield != null) parttomodifyfield.setvalue(parttomodify, field.getvalue(this)); } } }
Comments
Post a Comment