前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C# 快速高效率复制对象另一种方式 表达式树

C# 快速高效率复制对象另一种方式 表达式树

作者头像
郑子铭
发布2023-08-29 11:14:57
1910
发布2023-08-29 11:14:57
举报
文章被收录于专栏:DotNet NB && CloudNative

一、需求

在代码中经常会遇到需要把对象复制一遍,或者把属性名相同的值复制一遍。

比如:

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" };

我们需要给新的Student赋值

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 };

二、解决办法

当然最原始的办法就是把需要赋值的属性全部手动手写。

这样的效率是最高的。但是这样代码的重复率太高,而且代码看起来也不美观,更重要的是浪费时间,如果一个类有几十个属性,那一个一个属性赋值岂不是浪费精力,像这样重复的劳动工作更应该是需要优化的。

2.1、反射

反射应该是很多人用过的方法,就是封装一个类,反射获取属性和设置属性的值。

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);

调用一百万次耗时:2464毫秒

2.2、序列化

序列化的方式有很多种,有二进制、xml、json等等,今天我们就用Newtonsoft的json进行测试。

调用:

StudentSecond ss= JsonConvert.DeserializeObject<StudentSecond>(JsonConvert.SerializeObject(s));

调用一百万次耗时:2984毫秒

从这可以看出序列化和反射效率差别不大。

三、表达式树

3.1、简介

关于表达式树不了解的可以百度。

也就是说复制对象也可以用表达式树的方式。

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.2、分析代码

我们用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.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.4、利用泛型的特性再次优化代码

不用字典存储缓存,因为泛型就可以很容易解决这个问题。

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毫秒。

四、总结

从以上的测试和分析可以很容易得出,用表达式树是可以达到效率与书写方式二者兼备的方法之一,总之比传统的序列化和反射更加优秀。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2023-05-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 DotNet NB 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档