使用表达式目录树实现两个不同类型的属性赋值:
public class People { public int Age { get; set; } public string Name { get; set; } public int Id; } public class PeopleCopy { public int Age { get; set; } public string Name { get; set; } public int Id; } public class Class1 { private static Dictionary<string, object> _Dic = new Dictionary<string, object>(); private static TOut TransExp<TIn, TOut>(TIn tIn) { string key = $"funckey_{typeof(TIn).FullName}_{typeof(TOut).FullName}"; if (!_Dic.Keys.Contains(key)) { ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p"); List<MemberBinding> memberBindingList = new List<MemberBinding>(); foreach (var item in typeof(TOut).GetProperties()) { PropertyInfo propertyInfo = typeof(TIn).GetProperty(item.Name); if (propertyInfo == null) { continue; } MemberExpression property = Expression.Property(parameterExpression, propertyInfo); memberBindingList.Add(Expression.Bind(item, property)); } foreach (var item in typeof(TOut).GetFields()) { FieldInfo fieldInfo = typeof(TIn).GetField(item.Name); if (fieldInfo == null) { continue; } MemberExpression property = 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), new ParameterExpression[] { parameterExpression }); Func<TIn, TOut> func = expression.Compile(); _Dic.Add(key,func); } return ((Func < TIn, TOut > )_Dic[key])(tIn); } } static void Main(string[] args) { List<ClassLibrary1.PeopleCopy> PeoleCopyList = new List<ClassLibrary1.PeopleCopy>(); for (int i = 0; i < 5; i++) { ClassLibrary1.People people = new ClassLibrary1.People() { Id = 5+1, Age = 25, Name = "aaa"+i }; PeoleCopyList.Add(Class1.ToutGet<ClassLibrary1.People, ClassLibrary1.PeopleCopy>(people)); } }
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
分享文章:C#表达式目录树的应用详解-创新互联
转载来于:https://www.cdcxhl.com/article42/cejehc.html
成都网站建设公司_创新互联,为您提供定制网站、自适应网站、App设计、Google、用户体验、网站排名
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联