/// <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;
}
评论