class Program { static void Main(string[] args) { var people1 = new People(); people1.Age = 18; people1.IdCard = "410225"; var departMent = new Department() { Name = "計算機" }; people1.departMent = departMent; var people2 = people1.Clone(); Console.WriteLine(people2.Age); Console.WriteLine(people2.IdCard); Console.WriteLine(people2.departMent.Name); Console.WriteLine("變化啦!"); people1.Age = 18; people1.IdCard = "410225"; departMent.Name = "金融"; Console.WriteLine(people2.Age); Console.WriteLine(people2.IdCard); Console.WriteLine(people2.departMent.Name); Console.ReadLine(); } } [Serializable] public class People { public int Age{get;set;} public string IdCard{get;set;} public Department departMent{get;set;} public People Clone() { using (Stream ms = new MemoryStream()) { IFormatter forma = new BinaryFormatter(); forma.Serialize(ms, this); ms.Seek(0, SeekOrigin.Begin); return forma.Deserialize(ms) as People; } } } [Serializable] public class Department { public string Name{get;set;} }
實現了深度拷貝,不會由於Department中的Name變化而影響Department中的Name值this