Csharp/C#教程:C# 快速高效率复制对象(表达式树)分享

1、需求

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

比如:

publicclassStudent { publicintId{get;set;} publicstringName{get;set;} publicintAge{get;set;} } publicclassStudentSecond { publicintId{get;set;} publicstringName{get;set;} publicintAge{get;set;} }

Students=newStudent(){Age=20,Id=1,Name="Emrys"};

我们需要给新的Student赋值

Studentss=newStudent{Age=s.Age,Id=s.Id,Name=s.Name};

再或者给另一个类StudentSecond的属性赋值,两个类属性的名称和类型一致。

StudentSecondss=newStudentSecond{Age=s.Age,Id=s.Id,Name=s.Name};

2、解决办法

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

2.1、反射

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

privatestaticTOutTransReflection<TIn,TOut>(TIntIn) { TOuttOut=Activator.CreateInstance<TOut>(); foreach(varitemOutintOut.GetType().GetProperties()) { varitemIn=tIn.GetType().GetProperties().Where(i=>i.Name==itemOut.Name).FirstOrDefault(); if(itemIn!=null) { itemOut.SetValue(tOut,itemIn.GetValue(tIn)); } } returntOut; }

调用:StudentSecondss=TransReflection<Student,StudentSecond>(s);

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

2.2、序列化

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

调用:

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

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

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

3、表达式树

3.1、简介

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

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

Expression<Func<Student,StudentSecond>>ss=(x)=>newStudentSecond{Age=x.Age,Id=x.Id,Name=x.Name}; varf=ss.Compile(); StudentSecondstudentSecond=f(s);

这样的方式我们可以达到同样的效果。

有人说这样的写法和最原始的复制没有什么区别,代码反而变多了呢,这个只是第一步。

3.2、分析代码

我们用ILSpy反编译下这段表达式代码如下:

ParameterExpressionparameterExpression; Expression<Func<Student,StudentSecond>>ss=Expression.Lambda<Func<Student,StudentSecond>>(Expression.MemberInit(Expression.New(typeof(StudentSecond)),newMemberBinding[] { 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()))) }),newParameterExpression[] { parameterExpression }); Func<Student,StudentSecond>f=ss.Compile(); StudentSecondstudentSecond=f(s);

那么也就是说我们只要用反射循环所有的属性然后Expression.Bind所有的属性。最后调用Compile()(s)就可以获取正确的StudentSecond。

看到这有的人又要问了,如果用反射的话那岂不是效率很低,和直接用反射或者用序列化没什么区别吗?

当然这个可以解决的,就是我们的表达式树可以缓存。只是第一次用的时候需要反射,以后再用就不需要反射了。

3.3、复制对象通用代码

为了通用性所以其中的Student和StudentSecond分别泛型替换。

privatestaticDictionary<string,object>_Dic=newDictionary<string,object>(); privatestaticTOutTransExp<TIn,TOut>(TIntIn) { stringkey=string.Format("trans_exp_{0}_{1}",typeof(TIn).FullName,typeof(TOut).FullName); if(!_Dic.ContainsKey(key)) { ParameterExpressionparameterExpression=Expression.Parameter(typeof(TIn),"p"); List<MemberBinding>memberBindingList=newList<MemberBinding>(); foreach(varitemintypeof(TOut).GetProperties()) { MemberExpressionproperty=Expression.Property(parameterExpression,typeof(TIn).GetProperty(item.Name)); MemberBindingmemberBinding=Expression.Bind(item,property); memberBindingList.Add(memberBinding); } MemberInitExpressionmemberInitExpression=Expression.MemberInit(Expression.New(typeof(TOut)),memberBindingList.ToArray()); Expression<Func<TIn,TOut>>lambda=Expression.Lambda<Func<TIn,TOut>>(memberInitExpression,newParameterExpression[]{parameterExpression}); Func<TIn,TOut>func=lambda.Compile(); _Dic[key]=func; } return((Func<TIn,TOut>)_Dic[key])(tIn); }

调用:StudentSecondss=TransExp<Student,StudentSecond>(s);

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

4、上述就是C#学习教程:C# 快速高效率复制对象(表达式树)分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/907790.html

(0)
上一篇 2021年10月25日
下一篇 2021年10月25日

精彩推荐