ObjectHelper.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Reflection;
  6. namespace DirectService.Tools
  7. {
  8. public class ObjectHelper
  9. {
  10. /// <summary>
  11. /// 深度复制
  12. /// </summary>
  13. public static T DeepCopy<T>(T obj)
  14. {
  15. return Copy(obj, true);
  16. }
  17. /// <summary>
  18. /// 浅复制
  19. /// </summary>
  20. public static T ShallowCopy<T>(T obj)
  21. {
  22. return Copy(obj);
  23. }
  24. private static T Copy<T>(T obj, bool deep = false)
  25. {
  26. //如果是字符串或值类型则直接返回
  27. if (obj == null || obj.GetType().IsValueType || obj is string)
  28. {
  29. return obj;
  30. }
  31. object retval = Activator.CreateInstance(obj.GetType());
  32. if (obj is IDictionary)
  33. {
  34. var oriDic = obj as IDictionary;
  35. var newDic = retval as IDictionary;
  36. var enumerator = oriDic.GetEnumerator();
  37. while (enumerator.MoveNext())
  38. {
  39. newDic.Add(enumerator.Key, enumerator.Value);
  40. }
  41. }
  42. else if (obj is IList)
  43. {
  44. var oriList = obj as IList;
  45. var newList = retval as IList;
  46. foreach (var item in oriList)
  47. {
  48. newList.Add(item);
  49. }
  50. }
  51. else
  52. {
  53. var fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static).ToList();
  54. var type = obj.GetType();
  55. while ((type = type.BaseType) != typeof(object))
  56. {
  57. fields.AddRange(type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance));
  58. }
  59. foreach (FieldInfo field in fields)
  60. {
  61. if (field.IsLiteral)
  62. {
  63. continue;
  64. }
  65. try
  66. {
  67. var value = field.GetValue(obj);
  68. if (deep)
  69. {
  70. value = Copy(value, true);
  71. }
  72. field.SetValue(retval, value);
  73. }
  74. catch (Exception ex)
  75. {
  76. Trace.Write(string.Format("{0}\r\n属性:{1}\r\n异常:{2}", obj.GetType().FullName, field.Name, ex));
  77. }
  78. }
  79. }
  80. return (T)retval;
  81. }
  82. }
  83. }