SerializeHelper.cs 1.3 KB

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