当我尝试将对象转换为字节数组时,我得到了一个奇怪的数组。
这是代码:
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, obj);
Console.WriteLine(ByteArrayToString(ms.ToArray()));
}
//int obj = 50;
//string ByteArrayToString(byte[] byteArr) the functionality of this method is pretty obvious
结果是这样的:
“ 00 01 00 00 00 FF FF FF FF 01 00 00 00 00 00 00 00 04 01 00 00 00 0C 53 79 73 74 65 6D 2E 49 6E 74 33 32 01 00 00 00 07 6D 5F 76 61 6C 75 65 00 08 32 00 00 00 0B“
有人可以向我解释为什么吗::)最佳结果应该仅为“ 32 00 00 00”。
最佳答案
由于序列化程序需要提供足够的信息以反序列化数据,因此它必须包含一些有关要序列化的对象的元数据。具体来说,
53 79 73 74 65 6D 2E 49 6E 74 33 32
部分代表
System.Int32
如果改用
BinaryWriter
及其Write(Int32)
方法,则将获得所需的效果:您的内存流将仅包含整数中的四个字节。如果不知道在流中写入了Int32
,就无法反序列化。
关于c# - 对象到字节的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10485753/