【发布时间】:2020-11-12 07:29:05
【问题描述】:
在 .NET5 之前,我们通过这些代码序列化/反序列化字节/对象:
private static byte[] StructToBytes<T>(T t)
{
using (var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, t);
return ms.ToArray();
}
}
private static T BytesToStruct<T>(byte[] bytes)
{
using (var memStream = new MemoryStream())
{
var binForm = new BinaryFormatter();
memStream.Write(bytes, 0, bytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
var obj = binForm.Deserialize(memStream);
return (T)obj;
}
}
但出于安全原因,BinaryFormatter 将被删除:
https://docs.microsoft.com/zh-cn/dotnet/standard/serialization/binaryformatter-security-guide
那么有没有一些简单但高性能的方法来替代 BinaryFormatter?
【问题讨论】:
-
替换做什么?这个类是非常有问题的,通常很少使用,因为它允许将类型和代码注入应用程序。有很多方法可以以二进制格式序列化对象。现在最常见的一种是 gRPC 的 protobuf。大数据还有其他格式,例如 Parquet、Avro、ORC。
-
There's a probably duplicate question from 2010 询问 BinaryFormatter 替代方案。得益于 gRPC,Protobuf 现在比 2010 年更加普及
-
没有好的替代品。 XmlSerializer 太慢了,json 有时会出现继承问题。 Messagepack 完全不可靠。对于本地数据,没有什么比使用 binaryformatter 更快的了,而且它每次都能 100% 工作。
-
@juFo 相反,有一个很好的替代品,速度也快得多:Protocol Buffers