关于C#的深拷贝的实现方式:
①反射
②反序列化
③表达式树
目前只讲解利用反射实现C#深拷贝的方法:
深拷贝工具类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace CopyDemo
{
public sealed class CopyTools
{
public static T DeepCopy<T>(T obj)
{
//如果是字符串或值类型则直接返回
if (obj is string || obj.GetType().IsValueType) return obj;
object retval = Activator.CreateInstance(obj.GetType());
FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (FieldInfo field in fields)
{
try { field.SetValue(retval, DeepCopy(field.GetValue(obj))); }
catch { }
}
return (T)retval;
}
}
}
下面2个类用于测试:
宠物类->
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CopyDemo
{
public sealed class Pet
{
public string Name { get; set; }
}
}
人物类->
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CopyDemo
{
public sealed class People
{
public string Name { set; get; }
public Pet My_Pet { get; set; }
}
}
测试代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CopyDemo
{
public class Program
{
static void Main(string[] args)
{
People A = new People() {My_Pet = new Pet()};
A.Name = "Aonaufly";
A.My_Pet.Name = "小白";
Console.WriteLine("=================================================");
People _copyA = CopyTools.DeepCopy<People>(A);
_copyA.Name = "Kayer";
_copyA.My_Pet.Name = "旺财";
Console.WriteLine("源 name : {0} , petName : {1}" , A.Name,A.My_Pet.Name);
Console.WriteLine("Copy name : {0} , petName : {1}", _copyA.Name, _copyA.My_Pet.Name);
Console.ReadKey();
}
}
}
运行结果:
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。