我正在序列化一个流,它使用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 是一个流。
这里是 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
}
提前致谢!
答案 0 :(得分:0)
如果我没有正确理解你就可以这么写
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
类型的显式转换。