SerializationUtils.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using UnityEngine;
  3. using XGame.Framework.FileSystem;
  4. namespace XGame.Framework.Serialization
  5. {
  6. public static class SerializationUtils
  7. {
  8. public static T Read<T>(string filePath) where T : class, ISerializable
  9. {
  10. try
  11. {
  12. var bytes = File.ReadAllBytes(filePath);
  13. if (bytes != null)
  14. {
  15. EncryptXor(ref bytes, 1023);
  16. var reader = new Reader(bytes);
  17. var result = Activator.CreateInstance<T>();
  18. result.Deserialize(reader);
  19. return result;
  20. }
  21. }
  22. catch (Exception ex)
  23. {
  24. Debug.LogException(ex);
  25. }
  26. return default;
  27. }
  28. /// <summary>
  29. /// 反序列化
  30. /// </summary>
  31. /// <typeparam name="T"></typeparam>
  32. /// <param name="bytes"></param>
  33. /// <param name="xorKey"></param>
  34. /// <returns></returns>
  35. public static T Read<T>(byte[] bytes, uint xorKey = 0) where T : class, ISerializable
  36. {
  37. try
  38. {
  39. if (bytes != null)
  40. {
  41. if (xorKey != 0)
  42. {
  43. EncryptXor(ref bytes, xorKey);
  44. }
  45. var reader = new Reader(bytes);
  46. var result = Activator.CreateInstance<T>();
  47. result.Deserialize(reader);
  48. return result;
  49. }
  50. }
  51. catch (Exception ex)
  52. {
  53. Debug.LogException(ex);
  54. }
  55. return default;
  56. }
  57. /// <summary>
  58. /// 异或加密
  59. /// </summary>
  60. /// <param name="bytes"></param>
  61. /// <param name="key">默认为 1023</param>
  62. public static void EncryptXor(ref byte[] bytes, uint key)
  63. {
  64. if (bytes == null)
  65. return;
  66. for (var i = 0; i < bytes.Length; i++) // 依次对字符串中各字符进行操作
  67. {
  68. var current = bytes[i];
  69. bytes[i] = (byte)(current ^ key); // 将密钥与字符异或
  70. }
  71. }
  72. }
  73. }