/// <summary> /// 将当前对象的属性值复制到目标对象 /// </summary> /// <typeparam name="T">目标对象类型</typeparam> /// <param name="source">源对象</param> /// <param name="target">目标对象,如果为空,将生成一个</param> /// <param name="IsSerialize">是否深拷贝</param> /// <returns>复制过后的目标对象</returns> public static T FastCopy <T>(this object source, T target = default(T)) where T : new() { if (source == null) { throw new ArgumentNullException("source"); } if (target == null) { target = Activator.CreateInstance <T>(); } ModuleCast.GetCast(source.GetType(), typeof(T)).Cast(source, target); return(target); }
public static ModuleCast GetCast(Type targetType) { Dictionary <Type, ModuleCast> casts = GetModuleCast(targetType); ModuleCast result; if (!casts.TryGetValue(targetType, out result)) { lock (casts) { if (!casts.TryGetValue(targetType, out result)) { result = new ModuleCast(targetType); casts.Add(targetType, result); } } } return(result); }
/// <summary> /// DataTable转实体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="target"></param> /// <returns></returns> public static List <T> ToEntity <T>(this DataTable source) { if (source == null) { throw new ArgumentNullException("source"); } List <T> target = Activator.CreateInstance <List <T> >(); foreach (DataRow dr in source.Rows) { T t = Activator.CreateInstance <T>(); ModuleCast.GetCast(typeof(T)).Cast(dr, t); target.Add(t); } return(target); }
public static DataTable ToDataTable <T>(this List <T> list) { ModuleCast mc = ModuleCast.GetCast(typeof(T)); DataTable dt = new DataTable(); for (int i = 0; i < mc.mProperties.Count; i++) { try { dt.Columns.Add(mc.mProperties[i].TargetProperty.PropertyName, mc.mProperties[i].TargetProperty.PropertyType); } catch { } } foreach (T t in list) { DataRow dr = dt.NewRow(); ModuleCast.GetCast(typeof(T)).Cast(t, dr); dt.Rows.Add(dr); } return(dt); }
/// <summary> /// 转换对象 /// </summary> /// <typeparam name="TSource">源类型</typeparam> /// <typeparam name="TTarget">目标类型</typeparam> /// <param name="source">源对象</param> /// <param name="target">目标对象</param> public static void CastObject <TSource, TTarget>(TSource source, TTarget target) where TSource : class where TTarget : class { ModuleCast.GetCast(typeof(TSource), typeof(TTarget)).Cast(source, target); }