一、需求
在代码中常常会遇到须要把对象复制一遍,或者把属性名相同的值复制一遍。json
好比:缓存
public class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } public class StudentSecond { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } }
Student s = new Student() { Age = 20, Id = 1, Name = "Emrys" };app
咱们须要给新的Student赋值post
Student ss = new Student { Age = s.Age, Id = s.Id, Name = s.Name };测试
再或者给另外一个类StudentSecond的属性赋值,两个类属性的名称和类型一致。优化
StudentSecond ss = new StudentSecond { Age = s.Age, Id = s.Id, Name = s.Name };spa
二、解决办法
固然最原始的办法就是把须要赋值的属性所有手动手写。这样的效率是最高的。可是这样代码的重复率过高,并且代码看起来也不美观,更重要的是浪费时间,若是一个类有几十个属性,那一个一个属性赋值岂不是浪费精力,像这样重复的劳动工做更应该是须要优化的。code
2.一、反射
反射应该是不少人用过的方法,就是封装一个类,反射获取属性和设置属性的值。orm
private static TOut TransReflection<TIn, TOut>(TIn tIn) { TOut tOut = Activator.CreateInstance<TOut>(); var tInType = tIn.GetType(); foreach (var itemOut in tOut.GetType().GetProperties()) { var itemIn = tInType.GetProperty(itemOut.Name); ; if (itemIn != null) { itemOut.SetValue(tOut, itemIn.GetValue(tIn)); } } return tOut; }
调用:StudentSecond ss= TransReflection<Student, StudentSecond>(s);xml
调用一百万次耗时:2464毫秒
2.二、序列化
序列化的方式有不少种,有二进制、xml、json等等,今天咱们就用Newtonsoft的json进行测试。
调用:StudentSecond ss= JsonConvert.DeserializeObject<StudentSecond>(JsonConvert.SerializeObject(s));
调用一百万次耗时:2984毫秒
从这能够看出序列化和反射效率差异不大。
三、表达式树
3.一、简介
关于表达式树不了解的能够百度。
也就是说复制对象也能够用表达式树的方式。
Expression<Func<Student, StudentSecond>> ss = (x) => new StudentSecond { Age = x.Age, Id = x.Id, Name = x.Name }; var f = ss.Compile(); StudentSecond studentSecond = f(s);
这样的方式咱们能够达到一样的效果。
有人说这样的写法和最原始的复制没有什么区别,代码反而变多了呢,这个只是第一步。
3.二、分析代码
咱们用ILSpy反编译下这段表达式代码以下:
ParameterExpression parameterExpression; Expression<Func<Student, StudentSecond>> ss = Expression.Lambda<Func<Student, StudentSecond>>(Expression.MemberInit(Expression.New(typeof(StudentSecond)), new MemberBinding[] { Expression.Bind(methodof(StudentSecond.set_Age(int)), Expression.Property(parameterExpression, methodof(Student.get_Age()))), Expression.Bind(methodof(StudentSecond.set_Id(int)), Expression.Property(parameterExpression, methodof(Student.get_Id()))), Expression.Bind(methodof(StudentSecond.set_Name(string)), Expression.Property(parameterExpression, methodof(Student.get_Name()))) }), new ParameterExpression[] { parameterExpression }); Func<Student, StudentSecond> f = ss.Compile(); StudentSecond studentSecond = f(s);
那么也就是说咱们只要用反射循环全部的属性而后Expression.Bind全部的属性。最后调用Compile()(s)就能够获取正确的StudentSecond。
看到这有的人又要问了,若是用反射的话那岂不是效率很低,和直接用反射或者用序列化没什么区别吗?
固然这个能够解决的,就是咱们的表达式树能够缓存。只是第一次用的时候须要反射,之后再用就不须要反射了。
3.三、复制对象通用代码
为了通用性因此其中的Student和StudentSecond分别泛型替换。
private static Dictionary<string, object> _Dic = new Dictionary<string, object>(); private static TOut TransExp<TIn, TOut>(TIn tIn) { string key = string.Format("trans_exp_{0}_{1}", typeof(TIn).FullName, typeof(TOut).FullName); if (!_Dic.ContainsKey(key)) { ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p"); List<MemberBinding> memberBindingList = new List<MemberBinding>(); foreach (var item in typeof(TOut).GetProperties()) {
if (!item.CanWrite)
continue;
MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name)); MemberBinding memberBinding = Expression.Bind(item, property); memberBindingList.Add(memberBinding); } MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray()); Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression }); Func<TIn, TOut> func = lambda.Compile(); _Dic[key] = func; } return ((Func<TIn, TOut>)_Dic[key])(tIn); }
调用:StudentSecond ss= TransExp<Student, StudentSecond>(s);
调用一百万次耗时:564毫秒
3.四、利用泛型的特性再次优化代码
不用字典存储缓存,由于泛型就能够很容易解决这个问题。
public static class TransExpV2<TIn, TOut> { private static readonly Func<TIn, TOut> cache = GetFunc(); private static Func<TIn, TOut> GetFunc() { ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p"); List<MemberBinding> memberBindingList = new List<MemberBinding>(); foreach (var item in typeof(TOut).GetProperties()) {
if (!item.CanWrite)
continue;
MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name)); MemberBinding memberBinding = Expression.Bind(item, property); memberBindingList.Add(memberBinding); } MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray()); Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression }); return lambda.Compile(); } public static TOut Trans(TIn tIn) { return cache(tIn); } }
调用:StudentSecond ss= TransExpV2<Student, StudentSecond>.Trans(s);
调用一百万次耗时:107毫秒
耗时远远的小于使用automapper的338毫秒。
四、总结
从以上的测试和分析能够很容易得出,用表达式树是能够达到效率与书写方式两者兼备的方法之一,总之比传统的序列化和反射更加优秀。
最后望对各位有所帮助,本文原创,欢迎拍砖和推荐。