BinarySerializer.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using System.IO;
  2. using System.Text;
  3. using TBL.CSharp.Serialization.Utilities;
  4. namespace TBL.CSharp.Serialization.Marshal.Serializer
  5. {
  6. /// <summary>
  7. /// Marshal 风格的二进制序列化器
  8. /// </summary>
  9. public unsafe partial class BinarySerializer
  10. {
  11. /// <summary>
  12. /// 是否需要端序转换
  13. /// </summary>
  14. private readonly bool _isNeedEndianConversion;
  15. /// <summary>
  16. /// 构造序列化器
  17. /// </summary>
  18. /// <param name="isNeedEndianConversion">是否需要字节序转换</param>
  19. public BinarySerializer(bool isNeedEndianConversion)
  20. {
  21. _isNeedEndianConversion = isNeedEndianConversion;
  22. }
  23. /// <summary>
  24. /// 创建和此序列化器字节序适配的 <see cref="BinaryReader"/>
  25. /// </summary>
  26. public BinaryReader CreateBinaryReader(Stream stream) => _isNeedEndianConversion
  27. ? new BinaryReaderWithEndianConversion(stream, Encoding.UTF8, true)
  28. : new BinaryReader(stream, Encoding.UTF8, true);
  29. /// <summary>
  30. /// 创建和此序列化器字节序适配的 <see cref="BinaryWriter"/>
  31. /// </summary>
  32. public BinaryWriter CreateBinaryWriter(Stream stream) => _isNeedEndianConversion
  33. ? new BinaryWriterWithEndianConversion(stream, Encoding.UTF8, true)
  34. : new BinaryWriter(stream, Encoding.UTF8, true);
  35. }
  36. }