ObjectHelper.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // ***********************************************************************
  2. // <summary>
  3. //对象COPY/初始化帮助,通常是防止从视图中传过来的对象属性为空,这其赋初始值
  4. //</summary>
  5. // ***********************************************************************
  6. using System;
  7. using System.Reflection;
  8. namespace CommonTool
  9. {
  10. public static class ObjectHelper
  11. {
  12. public static T CopyTo<T>(this object source) where T:class, new()
  13. {
  14. var result = SetDefault(new T()) as T ?? new T();
  15. source.CopyTo(result);
  16. return result;
  17. }
  18. public static void CopyTo<T>(this object source, T target)
  19. where T : class,new()
  20. {
  21. if (source == null)
  22. return;
  23. if (target == null)
  24. {
  25. target = new T();
  26. }
  27. foreach (var property in target.GetType().GetProperties())
  28. {
  29. var propertyValue = source.GetType().GetProperty(property.Name).GetValue(source, null);
  30. if (propertyValue != null)
  31. {
  32. if (propertyValue.GetType().IsClass)
  33. {
  34. //EntityFactory.CreateEntity<> ();
  35. }
  36. target.GetType().InvokeMember(property.Name, BindingFlags.SetProperty, null, target, new[] { propertyValue });
  37. }
  38. }
  39. foreach (var field in target.GetType().GetFields())
  40. {
  41. var fieldValue = source.GetType().GetField(field.Name).GetValue(source);
  42. if (fieldValue != null)
  43. {
  44. target.GetType().InvokeMember(field.Name, BindingFlags.SetField, null, target, new[] { fieldValue });
  45. }
  46. }
  47. }
  48. private static object SetDefault(object obj)
  49. {
  50. PropertyInfo[] fields = obj.GetType().GetProperties();
  51. foreach (PropertyInfo v in fields)
  52. {
  53. if (v.PropertyType == typeof(string) && v.GetValue(obj) == null)
  54. {
  55. v.SetValue(obj, "");
  56. }
  57. else if (v.PropertyType == typeof(DateTime) && (v.GetValue(obj) == null || (DateTime)v.GetValue(obj) == DateTime.MinValue))
  58. {
  59. v.SetValue(obj, DateTime.Now);
  60. }
  61. //else if (v.PropertyType.IsClass && v.GetValue(obj) == null)
  62. //{
  63. // EntityFactory.CreateEntity<>();
  64. //}
  65. }
  66. return obj;
  67. }
  68. }
  69. public abstract class EntityFactory
  70. {
  71. public static T CreateEntity<T>() where T : class, new()
  72. {
  73. T t = Activator.CreateInstance<T>();
  74. PropertyInfo[] properties = typeof(T).GetProperties();
  75. foreach (PropertyInfo pi in properties)
  76. {
  77. Type type = pi.PropertyType;
  78. if (type.IsArray)
  79. {
  80. pi.SetValue(t, Activator.CreateInstance(type, 10), null);
  81. }
  82. else
  83. {
  84. pi.SetValue(t, Activator.CreateInstance(type), null);
  85. }
  86. }
  87. return t;
  88. }
  89. }
  90. }