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