合适使用深度拷贝的一个场景包含简单深度拷贝的示例代码
|
今天有一个场景需要用到对象的复制,写个深度拷贝的代码,做个记录
在同一个业务中包含多处回调的场景下:有一个对象是处理业务逻辑的回调中使用,但是在其他回调函数中会清理这个对象;
出现了一个问题在处理业务逻辑的回调函数中,还没有使用完,其他回调函数清空了这个对象,所有代码中尽量不要用锁,所以不考虑用锁的情况
考虑到主要业务处理回调逻辑比较独立;所以想到了2种方案,
- 线程内部对象
- 深度拷贝
因为业务处理回调函数执行时间很短,又没有等待逻辑,所以不合适使用线程池+线程内部对象的方式处理,所以在处理业务逻辑函数入口使用了对象的深度拷贝,保证了函数内部都使用的深度拷贝的对象;
深度拷贝的示例代码如下,留作备用:
- using System;
- using System.IO;
- using System.Runtime.Serialization.Formatters.Binary;
- namespace DeepCopyExample
- {
- [Serializable]
- public class Person
- {
- public string Name { get; set; }
- public int Age { get; set; }
- public Address Address { get; set; }
- public Person(string name, int age, Address address)
- {
- Name = name;
- Age = age;
- Address = address;
- }
- public Person DeepCopy()
- {
- using (MemoryStream stream = new MemoryStream())
- {
- BinaryFormatter formatter = new BinaryFormatter();
- formatter.Serialize(stream, this);
- stream.Position = 0;
- return (Person)formatter.Deserialize(stream);
- }
- }
- }
- [Serializable]
- public class Address
- {
- public string City { get; set; }
- public string Country { get; set; }
- public Address(string city, string country)
- {
- City = city;
- Country = country;
- }
- }
- internal class Program
- {
- static void Main(string[] args)
- {
- Address address = new Address("Beijing", "China");
- Person person1 = new Person("duwenlong ", 31, address);
- Person person2 = person1.DeepCopy();
- Console.WriteLine($"Person1 Name: {person1.Name}, Age: {person1.Age}, City: {person1.Address.City}, Country: {person1.Address.Country}");
- Console.WriteLine($"Person2 Name: {person2.Name}, Age: {person2.Age}, City: {person2.Address.City}, Country: {person2.Address.Country}");
- Console.WriteLine("changed Person2 City to Henan");
- person2.Address.City = "Henan";
- Console.WriteLine($"Person1 Name: {person1.Name}, Age: {person1.Age}, City: {person1.Address.City}, Country: {person1.Address.Country}");
- Console.WriteLine($"Person2 Name: {person2.Name}, Age: {person2.Age}, City: {person2.Address.City}, Country: {person2.Address.Country}");
- Console.ReadKey();
- }
- }
- }
复制代码 观察输出Persion2的城市修改了,Persion1的没有变化;
来源:https://www.cnblogs.com/duwenlong/archive/2023/03/15/17219528.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作! |
|
|
|
发表于 2023-3-15 21:39:44
举报
回复
分享
|
|
|
|