123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- namespace Ant.ORM.Tool
- {
- /// <summary>
- /// 两实体相互复制赋值以及两个集合相互转换
- /// //构造类1集合
- // TestClass1 test1 = new TestClass1();
- // List<TestClass1> class1 = new List<TestClass1>();
- // test1.Name ="lhc";
- // test1.ID =2;
- // class1.Add(test1);
- // //构造类2集合
- // TestClass2 test2 = new TestClass2();
- // List<TestClass2> class2 = new List<TestClass2>();
- // class2.Add(test2);
- // //两个集合相互转换
- // class2 = class1.ConvertAll<TestClass2>(new Converter<TestClass1, TestClass2>(c1 => new TestClass2() { Name = c1.Name}));//convert里面指定转换规则
- /// </summary>
- public class ModelCopyModel
- {
- #region 单个实体转换过程
- //转换规则
- //T代表要待转换的对象
- //M代表转换后的对象
- //参数中传入被转换的对象
- public static M InputToOutput<T, M>(T ObjT)
- where T : new()
- where M : new()
- // where M:ICollection<M>
- {
- 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 两个集合转换过程
- /// <summary>
- /// 两个实体LIST对拷
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <typeparam name="M"></typeparam>
- /// <param name="objTlist"></param>
- /// <returns></returns>
- public static List<M> ListInputToOutput<T, M>(List<T> objTlist)
- where T : new()
- where M : new()
- {
- //定义返回的集合
- List<M> ListM = new List<M>();
- //定义临时M类变量
- M TempM = new M();
- foreach (T item in objTlist)
- {
- TempM = InputToOutput<T, M>(item);
- ListM.Add(TempM);//加入结果集合
- }
- return ListM;
- }
- #endregion
- }
- }
|