使用表达式目录树实现两个不同类型的属性赋值:
publicclassPeople { publicintAge{get;set;} publicstringName{get;set;} publicintId; } publicclassPeopleCopy { publicintAge{get;set;} publicstringName{get;set;} publicintId; } publicclassClass1 { privatestaticDictionary<string,object>_Dic=newDictionary<string,object>(); privatestaticTOutTransExp<TIn,TOut>(TIntIn){ stringkey=$"funckey_{typeof(TIn).FullName}_{typeof(TOut).FullName}"; if(!_Dic.Keys.Contains(key)){ ParameterExpressionparameterExpression=Expression.Parameter(typeof(TIn),"p"); List<MemberBinding>memberBindingList=newList<MemberBinding>(); foreach(varitemintypeof(TOut).GetProperties()) { PropertyInfopropertyInfo=typeof(TIn).GetProperty(item.Name); if(propertyInfo==null){continue;} MemberExpressionproperty=Expression.Property(parameterExpression,propertyInfo); memberBindingList.Add(Expression.Bind(item,property)); } foreach(varitemintypeof(TOut).GetFields()) { FieldInfofieldInfo=typeof(TIn).GetField(item.Name); if(fieldInfo==null){continue;} MemberExpressionproperty=Expression.Field(parameterExpression,fieldInfo); memberBindingList.Add(Expression.Bind(item,property)); } Expression<Func<TIn,TOut>>expression=Expression.Lambda<Func<TIn,TOut>>(Expression.MemberInit(Expression.New(typeof(TOut)),memberBindingList),newParameterExpression[] { parameterExpression }); Func<TIn,TOut>func=expression.Compile(); _Dic.Add(key,func); } return((Func<TIn,TOut>)_Dic[key])(tIn); } } staticvoidMain(string[]args) { List<ClassLibrary1.PeopleCopy>PeoleCopyList=newList<ClassLibrary1.PeopleCopy>(); for(inti=0;i<5;i++) { ClassLibrary1.Peoplepeople=newClassLibrary1.People(){Id=5+1,Age=25,Name="aaa"+i}; PeoleCopyList.Add(Class1.ToutGet<ClassLibrary1.People,ClassLibrary1.PeopleCopy>(people)); } }
上述就是C#学习教程:C# 表达式目录树的应用详解分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/908120.html