今天在对字节流转换为对象时,发现总是会报错,后来查明原因是要将流的Index设置为起始位置,因为序列化后Index移到了
流的末尾,所以才报错了。代码如下:
public static T DeSerializer<T>(byte[] buffer, int length)
{ try { string mTextReceived = Encoding.UTF8.GetString(buffer, 0, length); SocketDataPack sdp = GetSocketDataPackFromString(mTextReceived);//MemoryStream对象提供了无需进行IO就可以创建Stream的方法
MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, sdp);//将流的Index设置为开始位置 stream.Position = 0;
// 确保书写器更新到Stream中;
stream.Flush(); object obj = formatter.Deserialize(stream); if (obj == null) { return default(T); } return (T)obj; } catch (Exception ex) { throw ex; } }