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值