winforms - Clone object without changing the values of the original object C# -
i need make copy of mygame class , use in simulation game trials before select move play.
for example :
public class mygame { private int start; private board board; //constructor public void play() { //play game } public object clone() { } } public class board { private int count; //constructor //some methods , properties public object clone() { } }
writing code method clone() have tried
- memberwiseclone()
- (board) this.memberwiseclone()
- board b = (board) this.board
i have read alot of articles , forums topic. answer people use deep cloning objects in c#, tried samples respect project still simulation modifying original object (mygame class) , not copy.
here have example deep copy, copies reference type objects used copy constructor:
public sealed class mygame { private int start; private board board; public mygame(mygame orig) { // value types - integers - can // reused this.start = orig.start; // reference types must clones seperately, // must not use orig.board directly here this.board = new board(orig.board); } } public sealed class board { private int count; public board(board orig) { // here have value type again this.count = orig.count; // here have no reference types. if did // we'd have clone them too, above } }
i think copy might somehow shallow , re-use references (like instance this.board = orig.board
instead of creating new board). guess though, can't see cloning implementation.
furthermore, used copy constructors instead of implementing icloneable
. implementation same. 1 advantage though simplify dealing subclasses:
suppose had myawesomegame : mygame
, not overriding mygame.clone
. myawesomegame.clone()
? actually, still new mygame
because mygame.clone
method in charge. 1 may carelessly expect cloned myawesomegame
here, however. new mygame(myawesomegame)
still copies somehow incompletely, it's more obvious. in example made classes sealed
avoid failures. if can seal them, there's change make life simpler.
implementing icloneable
not recommended in general, see why should implement icloneable in c#? more detailed , general information.
here have an icloneable
approach anyway, make things complete , enable compare , contrast:
public class mygame : icloneable { private int start; private board board; public object clone() { var copy = new mygame(); copy.start = this.start; copy.board = (board)this.board.clone(); return copy; } } public class board : icloneable { private int count; public object clone() { var copy = new board(); copy.count = this.count; return copy; } }
Comments
Post a Comment