我有这个可序列化的类:
[Serializable]
public class myClass
{
public byte myByte { get; set; }
public short myShort { get; set; }
public int myInt { get; set; }
}
知道 BYTE 类型是 1 字节,SHORT 类型是 2 字节,INT 类型是 4 字节,我正在等待 7 字节缓冲区,但使用以下代码,我得到了 232 字节的缓冲区大小:
myClass mc = new myClass { myByte = 0xff, myShort = 0x009c, myInt = 0x00000045 };
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, mc);
byte[] buffer = ms.ToArray();
我想通过 IP 发送“确切类型大小的缓冲区”,而无需使用如下代码:
byte[] exactBuffer = new byte[sizeof(byte) + sizeof(short) + sizeof(int)];
exactBuffer[0] = mc.myByte;
byte[] bmyShort = BitConverter.GetBytes(mc.myShort);
System.Buffer.BlockCopy(bmyShort, 0, exactBuffer, sizeof(byte), bmyShort.Length);
byte[] bmyInt = BitConverter.GetBytes(mc.myInt);
System.Buffer.BlockCopy(bmyInt, 0, exactBuffer, sizeof(byte)+sizeof(short), bmyInt.Length);
我需要这个类是一个类而不是一个结构。有什么办法吗?