Main idea – is correctly fill method Clone()
123
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IClonable2 { class Program { static void Main(string[] args) { } } public class PointDescription { public string Name { get; set; } public Guid ID { get; set; } public PointDescription() { Name = "No-name"; ID = Guid.NewGuid(); } } public class Point2 : ICloneable { public int X { get; set; } public int Y { get; set; } public Point2(int x, int y) { X = x; Y = y; } public Point2() { } public override string ToString() { //return base.ToString(); return string.Format("X={0},Y={1}", X, Y); } public object Clone() { return new Point(this.X, this.Y); // throw new NotImplementedException(); } } public class Point : ICloneable { public int X { get; set; } public int Y { get; set; } public PointDescription desc = new PointDescription(); public Point(int x, int y, string name) { X = x; Y = y; desc.Name = name; } public Point(int x, int y) { X = x; Y = y; } public Point() { } public override string ToString() { return string.Format("X={0},Y={1};Name={2};\nID={3}", X, Y, desc.Name, desc.ID); } public object Clone() { //return this.MemberwiseClone(); // << shallow copy, bad for this case !!! Point newPoint = (Point)this.MemberwiseClone(); // filling data PointDescription currentDesc = new PointDescription(); currentDesc.Name = this.desc.Name; newPoint.desc = currentDesc; return newPoint; // now OK!!! } } } |