Net Core教程

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

这篇关于C#中的浅表副本Clone与深拷贝Clone的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!