[Serializable] public class Person { public string Name { get; set; } public int Age { get; set; } public List<Person> Persons { get; set; } = new List<Person>(); //浅Clone public Person Clone() { return (Person)this.MemberwiseClone(); } //深Clone public Person DeepClone() { MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, this); stream.Position = 0; return formatter.Deserialize(stream) as Person; } }
说明:类型要特性成可序列化,浅Clone不能对List数组拷贝副本,深拷贝可以。测试如下
Person person = new Person(); person.Age = 30; person.Name = "she"; person.Persons.Add(new Person { Name = "ssss", Age = 1000 }); var my = person.Clone(); var deepPerson = person.DeepClone(); person.Persons[0].Name = "hhhh"; person.Persons[0].Age = 0; person.Name = "newshe"; person.Age = 100; MessageBox.Show($"person.Name={person.Name},person.age={person.Age}"); MessageBox.Show($"person.Persons[0].Name={my.Persons[0].Name},person.Persons[0].Age={my.Persons[0].Age}"); ; MessageBox.Show($"my.Name={my.Name},my.age={my.Age}"); ; MessageBox.Show($"my.Persons[0].Name={my.Persons[0].Name},my.Persons[0].Age={my.Persons[0].Age}"); ; MessageBox.Show($"deepPerson.Name={deepPerson.Name},deepPerson.age={deepPerson.Age}"); ; MessageBox.Show($"deepPerson.Persons[0].Name={deepPerson.Persons[0].Name},deepPerson.Persons[0].Age={deepPerson.Persons[0].Age}"); ;