ConvertHelper.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using System.Text;
  5. namespace WebAPIBase.Utils
  6. {
  7. /// <summary>
  8. /// 转换实体类
  9. /// </summary>
  10. public class ConvertHelper
  11. {
  12. /// <summary>
  13. /// list实体转换
  14. /// </summary>
  15. /// <typeparam name="T1"></typeparam>
  16. /// <typeparam name="T2"></typeparam>
  17. /// <param name="source"></param>
  18. /// <returns></returns>
  19. public static List<T2> ConvertToList<T1, T2>(List<T1> source)
  20. {
  21. List<T2> t2List = new List<T2>();
  22. if (source == null || source.Count == 0)
  23. return t2List;
  24. T2 model = default(T2);
  25. PropertyInfo[] pi = typeof(T2).GetProperties();
  26. PropertyInfo[] pi1 = typeof(T1).GetProperties();
  27. foreach (T1 t1Model in source)
  28. {
  29. model = Activator.CreateInstance<T2>();
  30. foreach (var p in pi)
  31. {
  32. foreach (var p1 in pi1)
  33. {
  34. if (p.Name == p1.Name)
  35. {
  36. p.SetValue(model, p1.GetValue(t1Model, null), null);
  37. break;
  38. }
  39. }
  40. }
  41. t2List.Add(model);
  42. }
  43. return t2List;
  44. }
  45. /// <summary>
  46. /// entity实体转换
  47. /// </summary>
  48. /// <typeparam name="T1"></typeparam>
  49. /// <typeparam name="T2"></typeparam>
  50. /// <param name="source"></param>
  51. /// <returns></returns>
  52. public static T2 ConvertToModel<T1, T2>(T1 source)
  53. {
  54. T2 model = default(T2);
  55. PropertyInfo[] pi = typeof(T2).GetProperties();
  56. PropertyInfo[] pi1 = typeof(T1).GetProperties();
  57. model = Activator.CreateInstance<T2>();
  58. foreach (var p in pi)
  59. {
  60. foreach (var p1 in pi1)
  61. {
  62. if (p.Name == p1.Name)
  63. {
  64. p.SetValue(model, p1.GetValue(source, null), null);
  65. break;
  66. }
  67. }
  68. }
  69. return model;
  70. }
  71. }
  72. }