ISerializable Interfaccia

Definizione

Consente a un oggetto di controllare la propria serializzazione e deserializzazione tramite serializzazione binaria e XML.

public interface class ISerializable
public interface ISerializable
[System.Runtime.InteropServices.ComVisible(true)]
public interface ISerializable
type ISerializable = interface
[<System.Runtime.InteropServices.ComVisible(true)>]
type ISerializable = interface
Public Interface ISerializable
Derivato
Attributi

Esempio

Nell'esempio di codice seguente viene illustrato l'uso dell'interfaccia ISerializable per definire il comportamento di serializzazione binaria personalizzato per una classe.

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.

[Serializable]
public ref class Singleton sealed: public ISerializable
{
private:

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

public:

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

private:

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

public:

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

   // A method called when serializing a Singleton.
   [System::Security::Permissions::SecurityPermissionAttribute
   (System::Security::Permissions::SecurityAction::LinkDemand, 
   Flags=System::Security::Permissions::SecurityPermissionFlag::SerializationFormatter)]
   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
};

[Serializable]
private ref class SingletonSerializationHelper sealed: public IObjectReference
{
public:

   // 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();
   }
};

[STAThread]
int main()
{
   FileStream^ fs = gcnew FileStream( "DataFile.dat",FileMode::Create );
   try
   {
      // 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 );
      throw;
   }
   finally
   {
      fs->Close();
   }

   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;

[Serializable]
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.
        Console.WriteLine("Done");
        Console.ReadLine();
    }

    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);
        s.Close();
    }

    public static void DeserializeItem(string fileName, IFormatter formatter)
    {
        FileStream s = new FileStream(fileName, FileMode.Open);
        MyItemType t = (MyItemType)formatter.Deserialize(s);
        Console.WriteLine(t.MyProperty);
    }
}
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
        Get
            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.
        Console.WriteLine("Done")
        Console.ReadLine()
    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)
        fs.Close()
    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)
        Console.WriteLine(myType.MyProperty)
    End Sub
End Class

Commenti

Qualsiasi classe che potrebbe essere serializzata usando la serializzazione binaria o XML deve essere contrassegnata con .SerializableAttribute Se una classe deve controllare il processo di serializzazione binario o XML, può implementare l'interfaccia ISerializable . Chiama Formatter l'oggetto in fase di serializzazione e popola l'oggetto GetObjectData fornito SerializationInfo con tutti i dati necessari per rappresentare l'oggetto. Crea Formatter un SerializationInfo oggetto con il tipo dell'oggetto nel grafico. Gli oggetti che devono inviare proxy per se stessi possono usare i FullTypeName metodi SerializationInfo e AssemblyName per modificare le informazioni trasmesse.

Nel caso dell'ereditarietà della classe, è possibile serializzare una classe che deriva da una classe di base che implementa ISerializable. In questo caso, la classe derivata deve chiamare l'implementazione della classe base di GetObjectData all'interno dell'implementazione di GetObjectData. In caso contrario, i dati della classe base non verranno serializzati.

L'interfaccia ISerializable implica un costruttore con la firma constructor (SerializationInfo information, StreamingContext context). Al momento della deserializzazione, il costruttore corrente viene chiamato solo dopo che i dati nell'oggetto SerializationInfo sono stati deserializzati dal formattatore. In generale, questo costruttore deve essere protected se la classe non sealedè .

Non è possibile garantire l'ordine in cui gli oggetti sono deserializzati. Ad esempio, se un tipo fa riferimento a un tipo che non è stato ancora deserializzato, si verificherà un'eccezione. Se si creano tipi con tali dipendenze, è possibile risolvere il problema implementando l'interfaccia IDeserializationCallback e il OnDeserialization metodo.

L'architettura di serializzazione gestisce i tipi di oggetto che estendono gli stessi tipi che estendono MarshalByRefObjectObject. Questi tipi possono essere contrassegnati con l'oggetto e implementano l'interfaccia SerializableAttributeISerializable come qualsiasi altro tipo di oggetto. Lo stato dell'oggetto verrà acquisito e mantenuto nel flusso.

Quando questi tipi vengono usati tramite System.Runtime.Remoting, l'infrastruttura di comunicazione remota fornisce un surrogato che impedisce la serializzazione tipica e serializza invece un proxy all'oggetto MarshalByRefObject. Un surrogato è un helper che sa come serializzare e deserializzare gli oggetti di un tipo specifico. Il proxy, invisibile all'utente nella maggior parte dei casi, sarà di tipo ObjRef.

Come modello di progettazione generale, sarebbe insolito che una classe sia contrassegnata con l'attributo serializzabile ed estende MarshalByRefObject. Gli sviluppatori devono considerare attentamente i possibili scenari di serializzazione e comunicazione remota quando si combinano queste due caratteristiche. Un esempio in cui può essere applicabile è con un MemoryStreamoggetto . Mentre la classe di base di MemoryStream (Stream) si estende da MarshalByRefObject, è possibile acquisire lo stato di un MemoryStream oggetto e ripristinarlo a volontà. Potrebbe quindi essere significativo serializzare lo stato di questo flusso in un database e ripristinarlo in un secondo momento. Tuttavia, quando viene usato tramite comunicazione remota, un oggetto di questo tipo sarà proxied.

Per altre informazioni sulla serializzazione delle classi che estendono MarshalByRefObject, vedere RemotingSurrogateSelector. Per altre informazioni sull'implementazione ISerializabledi , vedere Serializzazione personalizzata.

Nota

Questa interfaccia non si applica alla serializzazione JSON usando System.Text.Json.

Note per gli implementatori

Implementare questa interfaccia per consentire a un oggetto di partecipare alla propria serializzazione e deserializzazione.

Metodi

GetObjectData(SerializationInfo, StreamingContext)

Popola un oggetto SerializationInfo con i dati necessari per serializzare l'oggetto di destinazione.

Si applica a

Vedi anche