开发者

SerializableAttribute usage

I need to serialize a class C using BinaryFormatter.

So I mark C as [Serializable].

C inherits an abstract B class.

B is NOT marked as [Se开发者_开发问答rializable].

B inherits A class,

A is [Serializable] and also it implements ISerializable;

What situation can we have?

AProperty will be serialized

BProperty will not be serialized (?)

CProperty will be serialized


Your edit changes everything; if A implements ISerializable then they all implement ISerializable. With that, you are using custom serialization so the behaviour is determined entirely by the GetObjectData and serialization-constructor code you write in each of A / B / C.


Original answer, when there was no mention of ISerializable

serialization is generally based on type of the actual object at runtime, and BinaryFormatter (which maps to [Serializable]) is a field serializer. However, if B is not marked [Serializable], it cannot be serialized with BinaryFormatter (unless it is ISerializable); so:

  • if it is an A, all A fields will be serialized
  • if it is a C, it will throw an exception
  • (it can't be a B since that is abstract; but if it was, that would throw too)

If you aren't using BinaryFormatter (and personally I don't think BinaryFormatter is a good choice most of the time), then the behaviour will depend on the specific serializer.

My advice: use a different serializer; there are plenty. Almost all are (IMO) better choices than BinaryFormatter.


try using other Serialization techniques, like Google's Protofol Buffers, that saves you from rebuilding your whole app which consumes this serialized object when you change your AProperty class.

JSON is another option.


if A is a base class and it is serizable then B will automatically becomes serizable.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜