What is the point of the ISerializable interface?

后端 未结 4 1517
礼貌的吻别
礼貌的吻别 2020-11-29 00:06

It seems like I can serialize classes that don\'t have that interface, so I am unclear on its purpose.

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 00:42

    Classes can be serialized in .NET in one of two ways:

    1. Marking the class with SerializableAttribute and decorating all the fields that you don't want to be serialized with the NonSerialized attribute. (As Marc Gravell points out, BinaryFormatter, which is the class typically used to format ISerializable objects, automatically serializes all fields unless they are specifically marked otherwise.)
    2. Implementing the ISerializable interface for fully custom serialization.

    The former is simpler to use as it simply involves marking declarations with attributes, but is limited in its power. The latter allows more flexibility but takes significantly more effort to implement. Which one you should use depends completely on the context.

    Regarding the latter (ISerializable) and it usage, I've quoted from the MSDN page for the interface:

    Any class that might be serialized must be marked with the SerializableAttribute. If a class needs to control its serialization process, it can implement the ISerializable interface. The Formatter calls the GetObjectData at serialization time and populates the supplied SerializationInfo with all the data required to represent the object. The Formatter creates a SerializationInfo with the type of the object in the graph. Objects that need to send proxies for themselves can use the FullTypeName and AssemblyName methods on SerializationInfo to change the transmitted information.

    In the case of class inheritance, it is possible to serialize a class that derives from a base class that implements ISerializable. In this case, the derived class should call the base class implementation of GetObjectData inside its implementation of GetObjectData. Otherwise, the data from the base class will not be serialized.

提交回复
热议问题