我出于性能原因使用protobuf-net,其中反序列化已保存数据的程序集与序列化它的程序集相同.
我序列化的大多数类型都是使用ProtoContract和ProtoMember属性标记的简单契约,但偶尔我必须序列化具有许多子类的奇怪对象(即:Exception).
我使用经典的ISerializable机制使用以下解决方法.
我是protobuf-net的新手,想知道这是不是一个好主意,是否有更好/标准的方法来做到这一点.
我的解决方法:
我定义了一个实现经典序列化的通用代理
[ProtoContract] class BinarySerializationSurrogate<T> { [ProtoMember(1)] byte[] objectData = null; public static implicit operator T(BinarySerializationSurrogate<T> surrogate) { T ret = default(T); if (surrogate == null) return ret; var serializer = new BinaryFormatter(); using (var serializedStream = new MemoryStream(surrogate.objectData)) ret = (T)serializer.Deserialize(serializedStream); return ret; } public static implicit operator BinarySerializationSurrogate<T>(T obj) { if (obj == null) return null; var ret = new BinarySerializationSurrogate<T>(); var serializer = new BinaryFormatter(); using (var serializedStream = new MemoryStream()) { serializer.Serialize(serializedStream,obj); ret.objectData = serializedStream.ToArray(); } return ret; } }
RuntimeTypeModel.Default .Add(typeof(Exception),false) .SetSurrogate(typeof(BinarySerializationSurrogate<Exception>));
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。