c# - 如何反序列化 GZipStream?
问题描述
我正在序列化一个流,它使用 REST 服务存储在云中。序列化部分如下 -
public void serialize(Object obj, Stream str)
{
using (GZipStream zipStream = new GZipStream(str, CompressionMode.Compress, true))
{
if (obj is Stream)//This is executed in my case
{
((Stream)obj).CopyTo(zipStream);
}
else
{
binarySerializer.serialize(obj, zipStream);
}
}
}
参数obj是流内容,str是一个空流,它存储序列化流以供进一步使用。如果在我的情况下执行条件,因为obj是 Stream。
这是binarySerializer.Serialize()代码 -
public void serialize(object obj, Stream str)
{
if (obj is Stream)
{
((Stream)obj).CopyTo(str);
}
else
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(str, obj);
}
}
这工作正常,我可以使用Restlet Client chrome 扩展从云下载序列化文件(显示为带有下载选项的二进制文件)。
谁能帮我写反序列化部分?我想要具有以下签名的反序列化代码 -
public T deserialize<T>(Stream str)
{
//Code here
}
提前致谢!
解决方案
如果我没有理解你的意思,你可以这样写
public T deserialize<T>(Stream str) where T : class, new()
{
Type type = typeof(T);
if (type == typeof(Stream))
{
using (var bigStr = new GZipStream(str, CompressionMode.Decompress))
using (var outStream = new MemoryStream())
{
bigStr.CopyTo(outStream);
return outStream as T;
}
}
else
{
BinaryFormatter bin = new BinaryFormatter();
return (T)bin.Deserialize(str);
}
}
如果T
是 的类型Stream
,我们将反序列GZipStream
化为Stream
。其他情况我们使用简单的 BinaryFormatter。
在评论中的注释之后
public T Deserialize<T>(Stream str)
{
Type type = typeof(T);
if (type == typeof(Stream))
{
using (var bigStr = new GZipStream(str, CompressionMode.Decompress))
using (var outStream = new MemoryStream())
{
bigStr.CopyTo(outStream);
return (T)(outStream as object);
}
}
else
{
BinaryFormatter bin = new BinaryFormatter();
return (T)bin.Deserialize(str);
}
}
要从函数返回结果,我们首先从MemoryStream
类型转换为类型,object
然后我们可以使用从object
类型到T
类型的显式转换。
推荐阅读
- python - 元组的哈希函数如何工作
- jquery - 在 React 子组件中成功响应后,jQuery“.done”不会触发
- python - matplotlib 不错的情节,谁知道使用的方案?
- lua - 表大小差异。两个例子相同吗?
- terraform - terraform_remote_state 后端没有部分配置?
- c# - Azure Storage Queue.AddMessageAsync(item, cancelToken) 缺少接受两个参数的方法
- ssl - TLS1.3 版本不匹配
- java - Matrix Connected Cells:给定矩阵的位置,用数字 k 替换连接的单元格
- php - POSTMAN 导出不适用于 PHP cURL
- java - mchange-commons-java-0.2.11.jar 的 Spring Boot Web 应用 FileNotFoundException