在《使用C#将指定对象压缩并序列化为二进制》一文中介绍了如何将对象压缩并序列化为二进制,本文介绍相反的过程,即解压缩并反序列化(还原为对象)。
/// <summary> /// 将二进制反序列化为指定的类型。 /// </summary> /// <typeparam name="T">反序列化的目标类型。</typeparam> /// <param name="bytes">要反序列化的二进制数据。</param> /// <param name="isdecompress">是否解压缩。</param> public T DeserializeFromBytes<T>(byte[] bytes, bool isdecompress = true) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes)) { System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); if (isdecompress) { using (System.IO.Compression.DeflateStream ds = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress)) return (T)bf.Deserialize(ds); } else { return (T)bf.Deserialize(ms); } } }