SerializeHelper.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.IO;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4. using IwbZero.ToolCommon.LogHelpers;
  5. namespace IwbZero.ToolCommon.StringModel
  6. {
  7. public static class SerializeHelper
  8. {
  9. /// <summary>
  10. /// 深拷贝(对象需有[Serializable]可序列化特性)
  11. /// </summary>
  12. /// <typeparam name="T"></typeparam>
  13. /// <param name="target"></param>
  14. /// <returns></returns>
  15. public static T DeepClone<T>(this T target)
  16. {
  17. return IwbDerializable<T>(IwbSerializable(target));
  18. }
  19. public static string IwbSerializable(object target)
  20. {
  21. try
  22. {
  23. using (MemoryStream stream = new MemoryStream())
  24. {
  25. new BinaryFormatter().Serialize(stream, target);
  26. return Convert.ToBase64String(stream.ToArray());
  27. }
  28. }
  29. catch (Exception e)
  30. {
  31. typeof(SerializeHelper).LogError(e);
  32. return null;
  33. }
  34. }
  35. public static T IwbDerializable<T>(string target)
  36. {
  37. try
  38. {
  39. byte[] targetArray = Convert.FromBase64String(target);
  40. using (MemoryStream stream = new MemoryStream(targetArray))
  41. {
  42. return (T)new BinaryFormatter().Deserialize(stream);
  43. }
  44. }
  45. catch (Exception e)
  46. {
  47. typeof(SerializeHelper).LogError(e);
  48. return default(T);
  49. }
  50. }
  51. }
  52. }