工作记录
深拷贝:全新创建一个对象,值与复制对象一致,两个对象互不相关,修改一个对象不会影响到另一个对象
浅拷贝:全新创建一个对象,值与复制对象一致,两个对象相关,修改一个对象影响到另一个对象
在工作中需要将一个对象进行深拷贝:
做法1:使用反射
做法2:使用序列化
这里使用做法2 利用Newtonsoft.Json先对 对象做一次序列化,再做一次反序列化
添加Newtonsoft.Json引用
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace 使用序列化和反序列化来进行对象的深拷贝 { class Program { static void Main(string[] args) { test a = new test() { id = 1, name = "LXP1", age = 22 }; Console.WriteLine(a.ToString()); test b = a; a.name = "LXP2"; Console.WriteLine(a.ToString()); Console.WriteLine(b.ToString()); test c = new test() { id = 3, name = "LXP3", age = 33 }; test d = JsonConvert.DeserializeObject<test>( JsonConvert.SerializeObject(c)); c.name = "LXP33"; Console.WriteLine(d.ToString()); Console.Read(); } } class test { public int id { get; set; } public string name { get; set; } public int age { get; set; } public override string ToString() { return $"id={id},name={name},age={age}"; } } }