c# - How to create a copy of a Data Model -


in program trying make copy of data model can set data model of user control.

so far have tried setting new data model data model want copy, did aim both user controls same data model.

an example of did:

newusercontrol.newdatamodel = oldusercontrol.olddatamodel; 

how make copy of data model can set data model context of user control, without making ucs aim @ same data model?

one way create generic extension method. allows clone object regardless of type, long serializable (has 'serializable' attribute).

public static class objectextensions {         public static t clone<t>(this t source)     {             if (!typeof(t).isserializable)             {                 throw new argumentexception("this type must serializable.", "source");             }              if (object.referenceequals(source, null))                 return default(t);              iformatter formatter = new binaryformatter();             stream stream = new memorystream();             using (stream)             {                 formatter.serialize(stream, source);                 stream.seek(0, seekorigin.begin);                 return (t)formatter.deserialize(stream);             }      } } 

as @troelslarsen mentioned, there risk of copying event subscriptions. avoid can add nonserializedattribute fields don't want serialized. here msdn documentation example.

then use so:

newusercontrol.datamodel = olddatausercontrol.datamodel.clone(); 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -