C#对象深表复制方法
Posted taofengfeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#对象深表复制方法相关的知识,希望对你有一定的参考价值。
//反射 public 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,null),null); return tOut; //序列化 public static TOut TransJsonConvert<TIn, TOut>(TIn tIn) return JsonConvert.DeserializeObject<TOut>(JsonConvert.SerializeObject(tIn));
using System.Linq.Expressions; /// <summary> /// 表达式树实现的深表复制 /// </summary> /// <typeparam name="TIn"></typeparam> /// <typeparam name="TOut"></typeparam> public static class TransExp<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);
以上是关于C#对象深表复制方法的主要内容,如果未能解决你的问题,请参考以下文章