开发者

Serializing enum-like objects

开发者 https://www.devze.com 2023-03-21 02:33 出处:网络
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 additio

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 cl开发者_运维知识库ass 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

  1. Equality becomes easier, I can just use the default reference-comparing operators instead of having to override Equals, GetHashCode, ==, and != and implement IEquatable.

  2. 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.))


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 and bool value types.

0

精彩评论

暂无评论...
验证码 换一张
取 消