将类对象转换为字节并从字节创建对象

本文关键字:字节 创建对象 对象 转换 | 更新日期: 2023-09-27 18:35:33

我对这个主题做了一些研究,并在

  1. MemoryStream 和 BinaryFormatter 类
  2. 元帅级

但是这些方法都不适用于我的类,因为我的类有一个数组。

这是我正在使用的测试类:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public class ByteArrayInClass
{
    private byte _option;
    private ushort _nElements;
    private byte[] arrayElements;
    public ByteArrayInClass(byte option, ushort nElements)
    {
        this._option = option;
        this._nElements = nElements;
        arrayElements = new byte[nElements];
        for (int i = 0; i < arrayElements.Length; i++)
        {
            arrayElements[i] = (byte)i;
        }
    }
    public static byte[] ObjectToBytes(byteArrayInClass value)
    {
    }
    public static byteArrayInClass BytesToObject(byte[] bytes)
    {
    }
}

在我的主要:

testObject1 = new ByteArrayInClass(3, 10);
byte[] testBytes1 = ByteArrayInClass.ObjectToBytes(testObject1);
byte[] testBytes2 = { 3, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ByteArrayInClass testObject2 = ByteArrayInClass.BytesToObjectbyte(testBytes2);

我开始认为我需要将类的成员一一转换为字节,反之亦然才能将字节转换为对象。有人可以指出我正确的方向吗?

编辑:我不够清楚我要做什么。我正在开发一个与服务器通信的程序。它涉及接收数据和发送数据。数据以字节为单位发送和接收,当我收到字节的数据时,我需要用收到的字节构造一个类,这样我才能理解发送给我的内容。当我将数据发送到服务器时,我首先构造一个具有适当值的类,然后将对象转换为字节,以便我可以将数据发送到服务器。希望这能更好地解释我正在尝试做的事情。

似乎没有一种简单的方法可以将类转换为字节,因此我自己将每个类成员转换为字节。所以以下是我想出的。请随时让我知道这是否是完成任务的愚蠢方式。我想学习一种更聪明的方法。

public static int GetObjectSize(ByteArrayInClass value) 
{
    return Marshal.SizeOf(value.Option) + Marshal.SizeOf(value.ElementCount) + (value.ElementCount * 1);
}
public static byte[] ObjectToBytes(ByteArrayInClass value)
{
    int copyIndex = 0;
    byte[] resultBytes = new byte[GetObjectSize(value)];
    resultBytes[copyIndex] = value.Option;
    copyIndex += 1;
    byte[] elementCountBytes = BitConverter.GetBytes(value.ElementCount);
    elementCountBytes.CopyTo(resultBytes, copyIndex);
    copyIndex += elementCountBytes.Length;
    value.ElementArray.CopyTo(resultBytes, copyIndex);
    return resultBytes;
}

public static ByteArrayInClass BytesTObject(byte[] bytes)
{
    int convertIndex = 0;
    byte option = bytes[convertIndex];
    convertIndex += 1;
    ushort elementCount = BitConverter.ToUInt16(bytes, convertIndex);
    convertIndex += 2;
    ByteArrayInClass resultObj = new ByteArrayInClass(option, elementCount); 
    byte[] elementArray = new byte[elementCount];
    int j = 0;
    for (int i = convertIndex; i < (convertIndex + elementCount); i++)
    {
        elementArray[j++] = bytes[i];
    }
    resultObj.ElementArray = elementArray;
    return resultObj;
}

将类对象转换为字节并从字节创建对象

好的,

这可能是你要找的

从您的评论和更新中收集的假设如下

  • 您需要一种通用的方式来序列化类(消息)
  • 您希望能够通过线路(套接字,而不是 wcf)使用它
  • 它符合插座制度
  • 您需要一些基本的防止腐败的保护
  • 您希望它易于使用

注意:这里可能有很多可以改进的地方,但这只是给你一些想法

如果您使用类似 webservices 的东西,那么整个答案都是无效的,这实际上只是一种适用于套接字的 adhock 序列化方法

概述

Package 类具有一些用于以下的方法

  • 能够将对象序列化为字节
  • 能够将字节反序列化为对象
  • 可以创建带有标头信息的包
  • 标头包含您的消息类型(选项)
  • 整个包装的长度
  • 一些基本的检查求和和标记,如果发生损坏,您可以验证包

所以鉴于以下几点

消息枚举

// Some predefined messages
public enum MessageType : byte
{
   MyClass,
   MyOtherClass,
   Message3,
   Message4,
}

您想通过电汇发送的某些类

// a serilaizable class
// Make this as you like
[Serializable]
public class MyClass
{
   public byte[] SomeArbitaryBytes { get; set; }
   public string SomeArbitaryString { get; set; }
   public int SomeArbitaryInt { get; set; }
   public double SomeArbitaryDouble { get; set; }
   public MyClass()
   {
      SomeArbitaryString = "hello";
      SomeArbitaryInt = 7;
      SomeArbitaryDouble = 98.1;
      SomeArbitaryBytes = new byte[10];
      for (var i = 0; i < SomeArbitaryBytes.Length; i++)
      {
         SomeArbitaryBytes[i] = (byte)i;
      }
   }
}

包类

public static class Package
{
   // Method for basic checksum
   private static byte GetBasicChecksum(this byte[] data)
   {
      byte sum = 0;
      unchecked // Let overflow occur without exceptions
      {
         foreach (byte b in data)
         {
            sum += b;
         }
      }
      return sum;
   }
   // Serialize to bytes (BinaryFormatter)
   public static byte[] SerializeToBytes<T>(this T source)
   {
      using (var stream = new MemoryStream())
      {
         var formatter = new BinaryFormatter();
         formatter.Serialize(stream, source);
         return stream.ToArray();
      }
   }
   // Deerialize from bytes (BinaryFormatter)
   public static T DeserializeFromBytes<T>(this byte[] source)
   {
      using (var stream = new MemoryStream(source))
      {
         var formatter = new BinaryFormatter();
         stream.Seek(0, SeekOrigin.Begin);
         return (T)formatter.Deserialize(stream);
      }
   }
   // Check if we have enough data
   // will throw if it detects a corruption (basic)
   // return false if there isnt enough data to determine
   // return true and length of the package if sucessfull
   public static bool HasValidPackage(this Stream stream, out Int32 messageSize)
   {
      messageSize = -1;
      if (stream.Length - stream.Position < sizeof(byte) * 2 + sizeof(Int32))
         return false;

      var stx = stream.ReadByte();
      if (stx != 2)
         throw new InvalidDataException("Invalid Package : STX Failed");
      var packageLength = new byte[sizeof(Int32)];
      stream.Read(packageLength, 0, sizeof(Int32));
      messageSize = BitConverter.ToInt32(packageLength, 0) - sizeof(byte) * 3;
      var checkSum = stream.ReadByte();
      if (checkSum != packageLength.GetBasicChecksum())
         throw new InvalidDataException("Invalid Package : CheckSum Failed");
      return stream.Length >= messageSize;
   }
   // Pack the message
   public static byte[] PackMessage<T>(this T source, MessageType messageType)
   {
      var buffer = source.SerializeToBytes();
      var packageLength = BitConverter.GetBytes(buffer.Length + sizeof(byte) * 3);
      using (var stream = new MemoryStream())
      {
         stream.WriteByte(2);
         stream.Write(packageLength, 0, sizeof(Int32));
         stream.WriteByte(packageLength.GetBasicChecksum());
         stream.WriteByte((byte)messageType);
         stream.Write(buffer, 0, buffer.Length);
         stream.WriteByte(3);
         return stream.ToArray();
      }
   }
   // Unpack the message
   public static MessageType UnPackMessage(this Stream stream, Int32 messageSize, out byte[] buffer)
   {
      var messageType = (MessageType)stream.ReadByte();
      buffer = new byte[messageSize];
      stream.Read(buffer, 0, buffer.Length);
      var etx = stream.ReadByte();
      if (etx != 3)
         throw new InvalidDataException("Invalid Package : ETX Failed");
      return messageType;
   }
}

客户端代码

// create your class 
var myClass = new MyClass();
// Create a package out of it
var bytes = myClass.PackMessage(MessageType.MyClass);

服务器端代码

// this is server side
using (var stream = new MemoryStream(bytes))
{
   Int32 messageSize;
   // if we have a valid package do stuff
   // this loops until there isnt enough data for a package or empty
   while (stream.HasValidPackage(out messageSize))
   {
      byte[] buffer;
      switch (stream.UnPackMessage(messageSize, out buffer))
      {
         case MessageType.MyClass:
            var myClassCopy = buffer.DeserializeFromBytes<MyClass>();
            // do stuff with your class
            break;
         case MessageType.MyOtherClass:
            break;
         case MessageType.Message3:
            break;
         case MessageType.Message4:
            break;
         default:
            throw new ArgumentOutOfRangeException();
      }
   }
   // do something with the remaining bytes here, if any, i.e partial package
}

C# 不是 C/C++,所以你不能随心所欲地使用地址算术(据我所知)。

在.NET中,与字节数组相互转换的正确方法是序列化/反序列化。

或者,如果你想

模拟低级,也许你需要 BitConverter。

很难判断序列化是最终结果,还是只是用于尝试实现其他目标的方法。 步入其他目标。 但是,字节数组序列化得很好:

[Serializable]
public class ByteArrayClass
{
    public byte[] FirstArray {get; set;}
    public byte[] SecondArray {get; set;}           
}

然后做一个往返测试:

    ByteArrayClass myFoo = new ByteArrayClass();
    myFoo.FirstArray = new byte[] { 3, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    myFoo.SecondArray = new byte[] { 3, 11, 5, 1, 21, 23, 4, 5, 4, 7, 8, 9, 10 };
    using (FileStream fs = new FileStream(@"C:'Temp'Arry.Bin", 
                          FileMode.Create, FileAccess.Write))
    {
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(fs, myFoo);
    }
    ByteArrayInClass newFoo;
    using (FileStream fs = new FileStream(@"C:'Temp'Arry.Bin", 
                        FileMode.Open, FileAccess.Read))
    {
        BinaryFormatter bf = new BinaryFormatter();
        newFoo = (ByteArrayClass) bf.Deserialize(fs);
    }

如果我不补充ProtoBuf-Net是一个比BinaryFormatter更快,更好的序列化器,那将是我的失职。 它也更适合数据传输 - 由一个程序集序列化的类可以由另一个程序集反序列化,并且它产生的输出较小。

很难说你真正想要实现什么,但我会试一试。

这是否符合您的预期目标?

public class ByteArrayInClass
{
   public byte Option { get; set; }
   public ushort Elements { get; set; }
   public byte[] Bytes { get; set; }
   public ByteArrayInClass(byte option, ushort nElements)
   {
      this.Option = option;
      this.Elements = nElements;
      this.Bytes = new byte[nElements];
      for (var i = 0; i < nElements; i++)
      {
         this.Bytes[i] = (byte)i;
      }
   }
   public ByteArrayInClass(byte[] array)
   {
      this.Elements = (ushort)array.Length;
      this.Bytes = new byte[this.Elements];
      array.CopyTo(this.Bytes, 0);
   }
   public static byte[] ObjectToBytes(ByteArrayInClass value)
   {
      var result = new byte[value.Elements];
      value.Bytes.CopyTo(result, 0);
      return result;
   }
   public static ByteArrayInClass BytesToObject(byte[] bytes)
   {
      return new ByteArrayInClass(bytes);
   }
}