编程语言
首页 > 编程语言> > C#中的浅表副本Clone与深拷贝Clone

C#中的浅表副本Clone与深拷贝Clone

作者:互联网

[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}"); ;

标签:浅表,person,C#,Clone,deepPerson,Persons,my,Age,Name
来源: https://blog.csdn.net/qq_37189288/article/details/121292471