c# 复制对象
#region 复制对象 #region MyRegion private static Dictionary<string, object> _Dic = new Dictionary<string, object>(); public 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); } #endregion /// <summary> /// 将一个对象的属性给另一个对象的相同属性赋值 /// </summary> /// <typeparam name="S">源对象类型</typeparam> /// <typeparam name="T">目标对象类型</typeparam> /// <param name="s">源对象</param> /// <param name="t">目标对</param> public static void AutoMapping<S, T>(S s, T t) { try { #region 【方法1】历史使用方法,在2022年2月8日11:45:39停止使用,使用方法2 //if (s == null) //{ // s = default; // return; //} //if (t == null) //{ // t = default; // return; //} //PropertyInfo[] pps = GetPropertyInfos(s.GetType()); //Type target = typeof(T); //foreach (var pp in pps) //{ // PropertyInfo targetPP = target.GetProperty(pp.Name); // object value = pp.GetValue(s, null); // if (targetPP != null && value != null) // { // try // { // targetPP.SetValue(t, value, null); // } // catch (Exception) // { // } // } //} #endregion #region 【方法2】,2022-2-8 11:46:40开始启用 t = Com.Domain.Common.DataConvert.TransExp<S, T>(s); #endregion } catch (Exception) { } } /// <summary> /// 获取Service层的类实例,在没有写配置文件时使用 /// </summary> /// <typeparam name="T">当前传入的类名</typeparam> /// <returns>类实体</returns> public static T CreateInstance<T>() where T : new() { return new T(); } public static PropertyInfo[] GetPropertyInfos(Type type) { return type.GetProperties(BindingFlags.Public | BindingFlags.Instance); } #endregion