序列化类似枚举的对象
我正在使用二进制序列化(使用 BinaryFormatter 等)来序列化对象图。在这些对象中,有些对象具有类似于枚举的某种类型的字段,但具有附加属性和方法。
问题是每次反序列化这个类似枚举的对象时,都会创建该类型的一个新实例。是否有某种特殊的反序列化方法允许您返回一组现有对象中的一个,而不是创建一个全新的对象?
我听说过针对包含类枚举对象的每种类型执行此操作的方法,但我宁愿这样做,以便任何包含类枚举对象的类都会通过查找类枚举类型的现有对象来自动反序列化它。
(为什么我想要这个,以防万一
相等变得更容易,我可以只使用默认的引用比较运算符,而不必覆盖 Equals、GetHashCode、== 和 != 并实现 IEquatable。
- 中的一些数据 。类似枚举的对象可能会发生变化,并且我希望序列化的数据能够更新为新数据,而无需编写大量代码(请注意,类似枚举的对象中有一个字段永远不会更改。)
I am using binary serialization (with BinaryFormatter, etc) to serialize a graph of objects. Of those objects, some have fields of a certain type that is similar to an enumeration, except with additional properties and methods.
The problem that every time this enum-like object gets deserialized, a new instance of the type is created. Is there some sort of special deserialization method that allows you to return one of a set of existing objects, instead of creating a completely new one?
I've heard of ways to do this per type containing the enum-like object, but I would rather make it so that any class containing the enum-like object will automatically deserialize it by looking in the existing objects of the enum-like type.
(Why I want this, in case it matters
Equality becomes easier, I can just use the default reference-comparing operators instead of having to override Equals, GetHashCode, ==, and != and implement IEquatable.
Some of the data in the enum-like object may change, and I want the serialized data to update to the new data without lots of code. (Note that there is a field in the enum-like object that will never change.))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
ISerializationSurrogate
。请参阅此处获取一些示例代码。
更新
就我而言,我需要重新使用
SymbolId
和bool
值类型的现有(盒装)实例。You would do this with
ISerializationSurrogate
.See here for some example code.
Update
In my case, I need to re-use existing (boxed) instances for the
SymbolId
andbool
value types.