using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Ant.ORM.Tool { /// /// 两实体相互复制赋值以及两个集合相互转换 /// //构造类1集合 // TestClass1 test1 = new TestClass1(); // List class1 = new List(); // test1.Name ="lhc"; // test1.ID =2; // class1.Add(test1); // //构造类2集合 // TestClass2 test2 = new TestClass2(); // List class2 = new List(); // class2.Add(test2); // //两个集合相互转换 // class2 = class1.ConvertAll(new Converter(c1 => new TestClass2() { Name = c1.Name}));//convert里面指定转换规则 /// public class ModelCopyModel { #region 单个实体转换过程 //转换规则 //T代表要待转换的对象 //M代表转换后的对象 //参数中传入被转换的对象 public static M InputToOutput(T ObjT) where T : new() where M : new() // where M:ICollection { string tempName = string.Empty; //临时保存属性名称 //获取T的所有属性和值 //T t = new T(); M Result = new M(); //定义返回值 PropertyInfo[] propertys = Result.GetType().GetProperties(); //循环获取T的属性及其值 foreach (PropertyInfo pr in propertys) { tempName = pr.Name;//将属性名称赋值给临时变量 PropertyInfo findPro = ObjT.GetType().GetProperty(tempName);//从带转换实体获取属性 if (findPro != null) //如果获取到了:尝试执行赋值过程 { if (!pr.CanWrite) continue; //如果属性不可写,跳出 //取值:参数不匹配------------- object value = findPro.GetValue(ObjT, null); //如果为非空,则赋值给对象的属性 if (value != DBNull.Value) pr.SetValue(Result, value, null); } } return Result; } #endregion #region 两个集合转换过程 /// /// 两个实体LIST对拷 /// /// /// /// /// public static List ListInputToOutput(List objTlist) where T : new() where M : new() { //定义返回的集合 List ListM = new List(); //定义临时M类变量 M TempM = new M(); foreach (T item in objTlist) { TempM = InputToOutput(item); ListM.Add(TempM);//加入结果集合 } return ListM; } #endregion } }