static void Main(string[] args) { /* * ConcretePrototypeB prototype, copy; * prototype = new ConcretePrototypeB(); * //prototype.Attr = "Sunny"; * copy = (ConcretePrototypeB)prototype.Clone(); * //copy.Attr = "Tom"; * Console.WriteLine(prototype == copy); * //Console.WriteLine(prototype.GetType() == copy.GetType()); * Console.WriteLine(prototype.Member == copy.Member); * Console.Read(); */ WeeklyLog log_previous, log_new; log_previous = new WeeklyLog(); Attachment attachment = new Attachment(); log_previous.Attachment = attachment; log_new = log_previous.Clone(); Console.WriteLine("周报是否相同?{0}", (log_previous == log_new)?"是":"否"); Console.WriteLine("附件是否相同?{0}", (log_previous.Attachment == log_new.Attachment)?"是":"否"); Console.Read(); }
/// <summary> /// 客户端测试类 /// </summary> /// <param name="args"></param> static void Main(string[] args) { WeeklyLog log_pervious, log_new; log_pervious = new WeeklyLog(); Attachment attachment = new Attachment(); log_pervious.Attachment = attachment; log_new = log_pervious.Clone(); Console.WriteLine("周报是否相同?{0}", (log_pervious == log_new) ? "是" : "否"); Console.WriteLine("月报是否相同?{0}", (log_pervious.Attachment == log_new.Attachment) ? "是" : "否"); Console.ReadLine(); }
/* * //使用MemberwiseClone()方法实现浅克隆 * public WeeklyLog Clone() * { * return this.MemberwiseClone() as WeeklyLog; * } */ //使用序列化方式实现深克隆 public WeeklyLog Clone() { WeeklyLog clone = null; FileStream fs = new FileStream("Temp.dat", FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); try { formatter.Serialize(fs, this); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { fs.Close(); } FileStream fs1 = new FileStream("Temp.dat", FileMode.Open); BinaryFormatter formatter1 = new BinaryFormatter(); try { clone = (WeeklyLog)formatter1.Deserialize(fs1); } catch (SerializationException e) { Console.WriteLine("Failed to deserialize. Reason: " + e.Message); throw; } finally { fs.Close(); } return(clone); }