/// <summary> /// 自动映射父类数据到子类 /// </summary> /// <typeparam name="TParent"></typeparam> /// <typeparam name="TChild"></typeparam> /// <param name="parent"></param> /// <returns></returns> public static TChild AutoMapper<TParent, TChild>(TParent parent) where TChild : TParent, new() { TChild child = new TChild(); Type ParentType = typeof(TParent); var Properties = ParentType.GetRuntimeProperties(); foreach (PropertyInfo Propertie in Properties) { //循环遍历属性 if (Propertie.CanRead && Propertie.CanWrite) { //进行属性拷贝 Propertie.SetValue(child, Propertie.GetValue(parent, null), null); } } return child; } /// <summary> /// 没有继承约束,但是有共同属性,剪除部分属性后可视为目标属性 /// </summary> /// <typeparam name="TParent"></typeparam> /// <param name="me"></param> /// <returns></returns> public static TParent TryToParent<TParent>(this object me) where TParent : new() { TParent res = new TParent(); Type pt = typeof(TParent); try { var ps = pt.GetRuntimeProperties().ToList(); foreach (PropertyInfo p in ps) { //循环遍历属性 if (p.CanRead && p.CanWrite) { //进行属性拷贝 p.SetValue(res, p.GetValue(me, null), null); } } return res; } catch (Exception e) { throw new Exception($"实体转换失败,请检查属性是否一致{me?.GetType()?.Name}:{pt.Name}"); } }