CommonManager.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System;
  5. using System.Runtime.Serialization;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7. using System.IO;
  8. public class CommonManager : MonoSingleton<AudioManager>
  9. {
  10. public static string Serialize<T>(T obj)
  11. {
  12. try
  13. {
  14. IFormatter formatter = new BinaryFormatter();
  15. MemoryStream stream = new MemoryStream();
  16. formatter.Serialize(stream, obj);
  17. stream.Position = 0;
  18. byte[] buffer = new byte[stream.Length];
  19. stream.Read(buffer, 0, buffer.Length);
  20. stream.Flush();
  21. stream.Close();
  22. return System.Convert.ToBase64String(buffer);
  23. }
  24. catch (System.Exception ex)
  25. {
  26. throw new System.Exception("序列化失败,原因:" + ex.Message);
  27. }
  28. }
  29. public static T Desrialize<T>(T obj, string str)
  30. {
  31. try
  32. {
  33. obj = default(T);
  34. IFormatter formatter = new BinaryFormatter();
  35. byte[] buffer = System.Convert.FromBase64String(str);
  36. MemoryStream stream = new MemoryStream(buffer);
  37. obj = (T)formatter.Deserialize(stream);
  38. stream.Flush();
  39. stream.Close();
  40. }
  41. catch (System.Exception ex)
  42. {
  43. throw new System.Exception("反序列化失败,原因:" + ex.Message);
  44. }
  45. return obj;
  46. }
  47. }