InputToOutput.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. namespace Ant.ORM.Tool
  7. {
  8. /// <summary>
  9. /// 两实体相互复制赋值以及两个集合相互转换
  10. /// //构造类1集合
  11. // TestClass1 test1 = new TestClass1();
  12. // List<TestClass1> class1 = new List<TestClass1>();
  13. // test1.Name ="lhc";
  14. // test1.ID =2;
  15. // class1.Add(test1);
  16. // //构造类2集合
  17. // TestClass2 test2 = new TestClass2();
  18. // List<TestClass2> class2 = new List<TestClass2>();
  19. // class2.Add(test2);
  20. // //两个集合相互转换
  21. // class2 = class1.ConvertAll<TestClass2>(new Converter<TestClass1, TestClass2>(c1 => new TestClass2() { Name = c1.Name}));//convert里面指定转换规则
  22. /// </summary>
  23. public class ModelCopyModel
  24. {
  25. #region 单个实体转换过程
  26. //转换规则
  27. //T代表要待转换的对象
  28. //M代表转换后的对象
  29. //参数中传入被转换的对象
  30. public static M InputToOutput<T, M>(T ObjT)
  31. where T : new()
  32. where M : new()
  33. // where M:ICollection<M>
  34. {
  35. string tempName = string.Empty; //临时保存属性名称
  36. //获取T的所有属性和值
  37. //T t = new T();
  38. M Result = new M(); //定义返回值
  39. PropertyInfo[] propertys = Result.GetType().GetProperties();
  40. //循环获取T的属性及其值
  41. foreach (PropertyInfo pr in propertys)
  42. {
  43. tempName = pr.Name;//将属性名称赋值给临时变量
  44. PropertyInfo findPro = ObjT.GetType().GetProperty(tempName);//从带转换实体获取属性
  45. if (findPro != null) //如果获取到了:尝试执行赋值过程
  46. {
  47. if (!pr.CanWrite) continue; //如果属性不可写,跳出
  48. //取值:参数不匹配-------------
  49. object value = findPro.GetValue(ObjT, null);
  50. //如果为非空,则赋值给对象的属性
  51. if (value != DBNull.Value)
  52. pr.SetValue(Result, value, null);
  53. }
  54. }
  55. return Result;
  56. }
  57. #endregion
  58. #region 两个集合转换过程
  59. /// <summary>
  60. /// 两个实体LIST对拷
  61. /// </summary>
  62. /// <typeparam name="T"></typeparam>
  63. /// <typeparam name="M"></typeparam>
  64. /// <param name="objTlist"></param>
  65. /// <returns></returns>
  66. public static List<M> ListInputToOutput<T, M>(List<T> objTlist)
  67. where T : new()
  68. where M : new()
  69. {
  70. //定义返回的集合
  71. List<M> ListM = new List<M>();
  72. //定义临时M类变量
  73. M TempM = new M();
  74. foreach (T item in objTlist)
  75. {
  76. TempM = InputToOutput<T, M>(item);
  77. ListM.Add(TempM);//加入结果集合
  78. }
  79. return ListM;
  80. }
  81. #endregion
  82. }
  83. }