1. 浅拷贝
public class Person { public Person() { this.Address = new Address(); } public string Name { get; set; } public int Age { get; set; } public Address Address { get; set; } public Person Clone() { return (Person)this.MemberwiseClone(); } } public class Address { public string Street { get; set; } public string City { get; set; } }
2. 深拷贝
深拷贝是指不仅拷贝对象的值类型成员,而且还拷贝所有引用类型成员的实际对象。这意味着新的对象将拥有其引用类型成员的完全独立副本。
实现方式
- 反射
- 序列化
- 对象映射(三方开源如TinyMapper、AutoMapper)。
/// <summary> /// 深拷贝 /// </summary> public static void Copy2() { Person person1 = new Person() { Name = "张三", Address = new Address() { City = "北京", } }; //Person person2 = CreateDeepCopy(person1);//深拷贝1反射 // Person person2 =JsonConvert.DeserializeObject<Person>(JsonConvert.SerializeObject(person1));//深拷贝2序列化 Person person2 =person1.MapTo<Person,Person>();//深拷贝3对象映射 //修改原对象的属性 person1.Address.City = "上海"; //修改副本对象的属性 person2.Name = "李四"; person2.Address.City = "昆明"; string result = $"原对象{JsonConvert.SerializeObject(person1)}。副本{JsonConvert.SerializeObject(person2)}"; MessageBox.Show($"深拷贝:原对象和副本不相互影响。{result}"); } /// <summary> /// 使用反射进行深拷贝 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="original"></param> /// <returns></returns> static T CreateDeepCopy<T>(T original) { if (original == null) { return default(T); } Type type = original.GetType(); object newObject = Activator.CreateInstance(type); foreach (FieldInfo fieldInfo in type.GetFields()) { if (fieldInfo.IsStatic) { continue; } object value = fieldInfo.GetValue(original); fieldInfo.SetValue(newObject, CreateDeepCopy(value)); } return (T)newObject; }
标签:Person,C#,person2,对象,person1,Address,拷贝,public From: https://www.cnblogs.com/friend/p/18186405