How to do create a list of candidate objects in C#? -
i want find object best fits data. way i'm doing creating list of objects, each 1 tries fit data in different way, , @ end select 1 best fits data. this, created list of these objects, , want them same @ beginning, equal original object. way naively did just:
list <tryobject> tryobjects = new list<tryobject>(); for(int = 0; i< numberofdifferenttries; i++) { tryobjects.add(new trupbject()); tryobjects[i].dataobject = originaldataobject; tryobjects[i].blabla = blablu; ...other assignments tryobjects[i].trytofitthedata(); } //select tryobject in tryobjects[] fits data best , return it.
however, discovered doesn't work want, because each tryobjects[i].dataobject
reference originaldataobject
, whenever change each of dataobjects
, of change, plus original one.
i understand i'd need in case deep copy. however, methods found either use iclonable
or special methods hard copy, such serialization, take bit effort or can bring headaches.
so, since c# doesn't provide simple way this, assume it's because it's not designed solve problem in way.
so, question is, best way want in c#, following way wants me things?
so, since c# doesn't provide simple way this, assume it's because it's not designed solve problem in way.
that wrong. there way , described well: use icloneable
shallow copying or method serializing deep cloning. icloneable
here beginning of framework , commonly used.
i prefer using icloneable
as possible. quite easy write , easy in use.
this template use, since returns typed result of clone
, might come in handy:
public class someclass : icloneable { object icloneable.clone() { return this.clone(); } public someclass clone() { someclass otherinstance = new someclass(); // cloning here otherinstance.property = this.property; // end return otherinstance; } }
Comments
Post a Comment