1. 程式人生 > >位元組流轉換為物件的方法

位元組流轉換為物件的方法

今天在對位元組流轉換為物件時,發現總是會報錯,後來查明原因是要將流的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;
            }
        }