ISerializable Interface


Permet à un objet de contrôler ses propres sérialisation et désérialisation.Allows an object to control its own serialization and deserialization.

public interface class ISerializable
public interface ISerializable
public interface ISerializable
type ISerializable = interface
type ISerializable = interface
Public Interface ISerializable


L’exemple de code suivant illustre l’utilisation de l' ISerializable interface pour définir le comportement de sérialisation personnalisé d’une classe.The following code example demonstrates the use of the ISerializable interface to define custom serialization behavior for a class.

using namespace System;
using namespace System::IO;
using namespace System::Collections;
using namespace System::Runtime::Serialization::Formatters::Binary;
using namespace System::Runtime::Serialization;

ref class SingletonSerializationHelper;

// There should be only one instance of this type per AppDomain.

public ref class Singleton sealed: public ISerializable

   // This is the one instance of this type.
   static Singleton^ theOneObject = gcnew Singleton;


   // Here are the instance fields.
   String^ someString;
   Int32 someNumber;


   // Private constructor allowing this type to construct the singleton.
      // Do whatever is necessary to initialize the singleton.
      someString = "This is a String* field";
      someNumber = 123;


   // A method returning a reference to the singleton.
   static Singleton^ GetSingleton()
      return theOneObject;

   // A method called when serializing a Singleton.
   virtual void GetObjectData( SerializationInfo^ info, StreamingContext context )
      // Instead of serializing this Object*, we will  
      // serialize a SingletonSerializationHelp instead.
      info->SetType( SingletonSerializationHelper::typeid );

      // No other values need to be added.

   // NOTE: ISerializable*'s special constructor is NOT necessary 
   // because it's never called

private ref class SingletonSerializationHelper sealed: public IObjectReference

   // This Object* has no fields (although it could).
   // GetRealObject is called after this Object* is deserialized
   virtual Object^ GetRealObject( StreamingContext context )
      // When deserialiing this Object*, return a reference to 
      // the singleton Object* instead.
      return Singleton::GetSingleton();

int main()
   FileStream^ fs = gcnew FileStream( "DataFile.dat",FileMode::Create );
      // Construct a BinaryFormatter and use it 
      // to serialize the data to the stream.
      BinaryFormatter^ formatter = gcnew BinaryFormatter;

      // Create an array with multiple elements refering to 
      // the one Singleton Object*.
      array<Singleton^>^a1 = {Singleton::GetSingleton(),Singleton::GetSingleton()};

      // This displays S"True".
      Console::WriteLine( "Do both array elements refer to the same Object? {0}", (a1[ 0 ] == a1[ 1 ]) );

      // Serialize the array elements.
      formatter->Serialize( fs, a1 );

      // Deserialize the array elements.
      fs->Position = 0;
      array<Singleton^>^a2 = (array<Singleton^>^)formatter->Deserialize( fs );

      // This displays S"True".
      Console::WriteLine( "Do both array elements refer to the same Object? {0}", (a2[ 0 ] == a2[ 1 ]) );

      // This displays S"True".
      Console::WriteLine( "Do all  array elements refer to the same Object? {0}", (a1[ 0 ] == a2[ 0 ]) );
   catch ( SerializationException^ e ) 
      Console::WriteLine( "Failed to serialize. Reason: {0}", e->Message );

   return 0;
using System;
using System.Text;
using System.IO;
// Add references to Soap and Binary formatters.
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap ;
using System.Runtime.Serialization;

public class MyItemType : ISerializable
    public MyItemType()
        // Empty constructor required to compile.

    // The value to serialize.
    private string myProperty_value;

    public string MyProperty
        get { return myProperty_value; }
        set { myProperty_value = value; }

    // Implement this method to serialize data. The method is called
    // on serialization.
    public void GetObjectData(SerializationInfo info, StreamingContext context)
        // Use the AddValue method to specify serialized values.
        info.AddValue("props", myProperty_value, typeof(string));

    // The special constructor is used to deserialize values.
    public MyItemType(SerializationInfo info, StreamingContext context)
        // Reset the property value using the GetValue method.
        myProperty_value = (string) info.GetValue("props", typeof(string));

// This is a console application.
public static class Test
    static void Main()
        // This is the name of the file holding the data. You can use any file extension you like.
        string fileName = "dataStuff.myData";

        // Use a BinaryFormatter or SoapFormatter.
        IFormatter formatter = new BinaryFormatter();
        //IFormatter formatter = new SoapFormatter();

        Test.SerializeItem(fileName, formatter); // Serialize an instance of the class.
        Test.DeserializeItem(fileName, formatter); // Deserialize the instance.

    public static void SerializeItem(string fileName, IFormatter formatter)
        // Create an instance of the type and serialize it.
        MyItemType t = new MyItemType();
        t.MyProperty = "Hello World";

        FileStream s = new FileStream(fileName , FileMode.Create);
        formatter.Serialize(s, t);

    public static void DeserializeItem(string fileName, IFormatter formatter)
        FileStream s = new FileStream(fileName, FileMode.Open);
        MyItemType t = (MyItemType)formatter.Deserialize(s);
Imports System.Text
Imports System.IO

' Add references to Soap and Binary formatters.
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization.Formatters.Soap
Imports System.Runtime.Serialization

<Serializable()> _
Public Class MyItemType
    Implements ISerializable
    ' Empty constructor required to compile.
    Public Sub New()
    End Sub

    ' The value to serialize.
    Private myProperty_value As String

    Public Property MyProperty() As String
            Return myProperty_value
        End Get
        Set(value As String)
            myProperty_value = value
        End Set
    End Property

    ' Implement this method to serialize data. The method is called 
    ' on serialization.
    Public Sub GetObjectData(info As SerializationInfo, context As StreamingContext) Implements ISerializable.GetObjectData
        ' Use the AddValue method to specify serialized values.
        info.AddValue("props", myProperty_value, GetType(String))

    End Sub

    ' The special constructor is used to deserialize values.
    Public Sub New(info As SerializationInfo, context As StreamingContext)
        ' Reset the property value using the GetValue method.
        myProperty_value = DirectCast(info.GetValue("props", GetType(String)), String)
    End Sub
End Class

' This is a console application. 
Public Class Test

    Public Shared Sub Main()
        ' This is the name of the file holding the data. You can use any file extension you like.
        Dim fileName As String = "dataStuff.myData"

        ' Use a BinaryFormatter or SoapFormatter.
        Dim formatter As IFormatter = New BinaryFormatter()
        ' Dim formatter As IFormatter = New SoapFormatter()

        Test.SerializeItem(fileName, formatter)
        ' Serialize an instance of the class.
        Test.DeserializeItem(fileName, formatter)
        ' Deserialize the instance.
    End Sub

    Public Shared Sub SerializeItem(fileName As String, formatter As IFormatter)
        ' Create an instance of the type and serialize it.
        Dim myType As New MyItemType()
        myType.MyProperty = "Hello World"

        Dim fs As New FileStream(fileName, FileMode.Create)
        formatter.Serialize(fs, myType)
    End Sub

    Public Shared Sub DeserializeItem(fileName As String, formatter As IFormatter)
        Dim fs As New FileStream(fileName, FileMode.Open)

        Dim myType As MyItemType = DirectCast(formatter.Deserialize(fs), MyItemType)
    End Sub
End Class


Toute classe qui peut être sérialisée doit être marquée avec SerializableAttribute .Any class that might be serialized must be marked with the SerializableAttribute. Si une classe doit contrôler son processus de sérialisation, elle peut implémenter l' ISerializable interface.If a class needs to control its serialization process, it can implement the ISerializable interface. FormatterAppelle le GetObjectData au moment de la sérialisation et remplit le fourni SerializationInfo avec toutes les données requises pour représenter l’objet.The Formatter calls the GetObjectData at serialization time and populates the supplied SerializationInfo with all the data required to represent the object. FormatterCrée un SerializationInfo avec le type de l’objet dans le graphique.The Formatter creates a SerializationInfo with the type of the object in the graph. Les objets qui doivent envoyer des proxys pour eux-mêmes peuvent utiliser les FullTypeName AssemblyName méthodes et sur SerializationInfo pour modifier les informations transmises.Objects that need to send proxies for themselves can use the FullTypeName and AssemblyName methods on SerializationInfo to change the transmitted information.

Dans le cas de l’héritage de classe, il est possible de sérialiser une classe qui dérive d’une classe de base qui implémente ISerializable .In the case of class inheritance, it is possible to serialize a class that derives from a base class that implements ISerializable. Dans ce cas, la classe dérivée doit appeler l’implémentation de la classe de base de GetObjectData à l’intérieur de son implémentation de GetObjectData .In this case, the derived class should call the base class implementation of GetObjectData inside its implementation of GetObjectData. Dans le cas contraire, les données de la classe de base ne seront pas sérialisées.Otherwise, the data from the base class will not be serialized.

L' ISerializable interface implique un constructeur avec le constructeur de signature ( SerializationInfo informations, StreamingContext contexte).The ISerializable interface implies a constructor with the signature constructor (SerializationInfo information, StreamingContext context). Au moment de la désérialisation, le constructeur actuel est appelé uniquement une fois que les données du SerializationInfo ont été désérialisées par le formateur.At deserialization time, the current constructor is called only after the data in the SerializationInfo has been deserialized by the formatter. En général, ce constructeur doit être protégé si la classe n’est pas sealed.In general, this constructor should be protected if the class is not sealed.

L’ordre dans lequel les objets sont désérialisés ne peut pas être garanti.The order in which objects are deserialized cannot be guaranteed. Par exemple, si un type fait référence à un type qui n’a pas encore été désérialisé, une exception se produit.For example, if one type references a type that has not been deserialized yet, an exception will occur. Si vous créez des types qui ont des dépendances de ce type, vous pouvez contourner le problème en implémentant l' IDeserializationCallback interface et la OnDeserialization méthode.If you are creating types that have such dependencies, you can work around the problem by implementing the IDeserializationCallback interface and the OnDeserialization method.

L’architecture de sérialisation gère les types d’objets qui étendent MarshalByRefObject les mêmes que les types qui étendent Object .The serialization architecture handles object types that extend MarshalByRefObject the same as types that extend Object. Ces types peuvent être marqués avec SerializableAttribute et implémentent l' ISerializable interface comme tout autre type d’objet.These types can be marked with the SerializableAttribute and implement the ISerializable interface as any other object type. Leur état d’objet sera capturé et conservé dans le flux.Their object state will be captured and persisted onto the stream.

Lorsque ces types sont utilisés via System.Runtime.Remoting , l’infrastructure de communication à distance fournit un substitut qui prévaut pour la sérialisation classique et sérialise à la place un proxy vers le MarshalByRefObject .When these types are being used through System.Runtime.Remoting, the remoting infrastructure provides a surrogate that preempts typical serialization and instead serializes a proxy to the MarshalByRefObject. Un substitut est une assistance qui sait comment sérialiser et désérialiser des objets d’un type particulier.A surrogate is a helper that knows how to serialize and deserialize objects of a particular type. Le proxy, invisible pour l’utilisateur dans la plupart des cas, est de type ObjRef .The proxy, invisible to the user in most cases, will be of type ObjRef.

En guise de modèle de conception général, il serait rare qu’une classe soit marquée avec l’attribut Serializable et étende MarshalByRefObject .As a general design pattern, it would be unusual for a class to be both marked with the serializable attribute and extend MarshalByRefObject. Les développeurs doivent réfléchir soigneusement aux scénarios de sérialisation et de communication à distance possibles lors de la combinaison de ces deux caractéristiques.Developers should think carefully about the possible serialization and remoting scenarios when combining these two characteristics. Un exemple peut s’appliquer à un MemoryStream .One example where this might be applicable is with a MemoryStream. Bien que la classe de base de MemoryStream ( Stream ) s’étende de MarshalByRefObject , il est possible de capturer l’état d’un et de le MemoryStream restaurer à partir de.While the base class of MemoryStream (Stream) extends from MarshalByRefObject, it is possible to capture the state of a MemoryStream and restore it at will. Il peut donc être utile de sérialiser l’état de ce flux dans une base de données et de le restaurer ultérieurement dans le temps.It might, therefore, be meaningful to serialize the state of this stream into a database and restore it at some later point in time. Toutefois, quand il est utilisé via la communication à distance, un objet de ce type est proxy.However, when used through remoting, an object of this type would be proxied.

Pour plus d’informations sur la sérialisation des classes qui étendent MarshalByRefObject , consultez RemotingSurrogateSelector .For more information about serialization of classes that extend MarshalByRefObject, see RemotingSurrogateSelector. Pour plus d’informations sur l’implémentation de ISerializable , consultez sérialisation personnalisée.For more information about implementing ISerializable, see Custom Serialization.

Notes pour les responsables de l’implémentation

Implémentez cette interface pour permettre à un objet de participer à sa propre sérialisation et désérialisation.Implement this interface to allow an object to take part in its own serialization and deserialization.


GetObjectData(SerializationInfo, StreamingContext)

Remplit un SerializationInfo avec les données requises pour sérialiser l'objet cible.Populates a SerializationInfo with the data needed to serialize the target object.

S’applique à

Voir aussi