ISerializable Rozhraní

Definice

Umožňuje objektu řídit svou vlastní serializaci a deserializaci.Allows an object to control its own serialization and deserialization.

public interface class ISerializable
public interface ISerializable
[System.Runtime.InteropServices.ComVisible(true)]
public interface ISerializable
type ISerializable = interface
Public Interface ISerializable
Odvozené
Atributy

Příklady

Následující příklad kódu ukazuje použití rozhraní ISerializable k definování vlastního chování serializace pro třídu.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.

[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

Poznámky

Všechny třídy, které mohou být serializovány, musí být označeny SerializableAttribute.Any class that might be serialized must be marked with the SerializableAttribute. Pokud třída potřebuje řídit svůj proces serializace, může implementovat rozhraní ISerializable.If a class needs to control its serialization process, it can implement the ISerializable interface. Formatter volá GetObjectData v době serializace a naplní dodaný SerializationInfo všemi daty potřebnými k reprezentaci objektu.The Formatter calls the GetObjectData at serialization time and populates the supplied SerializationInfo with all the data required to represent the object. Formatter vytvoří SerializationInfo s typem objektu v grafu.The Formatter creates a SerializationInfo with the type of the object in the graph. Objekty, které potřebují posílat proxy pro sebe, mohou pomocí FullTypeName a AssemblyName na SerializationInfo měnit přenesené informace.Objects that need to send proxies for themselves can use the FullTypeName and AssemblyName methods on SerializationInfo to change the transmitted information.

V případě dědičnosti třídy je možné serializovat třídu, která je odvozena ze základní třídy, která implementuje ISerializable.In the case of class inheritance, it is possible to serialize a class that derives from a base class that implements ISerializable. V tomto případě by měla odvozená třída volat implementaci GetObjectData základní třídy v rámci její implementace GetObjectData.In this case, the derived class should call the base class implementation of GetObjectData inside its implementation of GetObjectData. Jinak nebudou data ze základní třídy serializována.Otherwise, the data from the base class will not be serialized.

Rozhraní ISerializable implikuje konstruktor s konstruktorem signatury (SerializationInfo informace, StreamingContext Context).The ISerializable interface implies a constructor with the signature constructor (SerializationInfo information, StreamingContext context). V době deserializace je aktuální konstruktor volán pouze poté, co byla data v SerializationInfo deserializována pomocí formátovacího modulu.At deserialization time, the current constructor is called only after the data in the SerializationInfo has been deserialized by the formatter. Obecně by tento konstruktor měl být chráněn, pokud třída není zapečetěná.In general, this constructor should be protected if the class is not sealed.

Pořadí, ve kterém jsou objekty deserializovány, nelze zaručit.The order in which objects are deserialized cannot be guaranteed. Například pokud jeden typ odkazuje na typ, který ještě nebyl deserializován, dojde k výjimce.For example, if one type references a type that has not been deserialized yet, an exception will occur. Pokud vytváříte typy, které mají tyto závislosti, můžete problém obejít implementací rozhraní IDeserializationCallback a metody OnDeserialization.If you are creating types that have such dependencies, you can work around the problem by implementing the IDeserializationCallback interface and the OnDeserialization method.

Architektura serializace zpracovává typy objektů, které přesahují MarshalByRefObject stejné jako typy, které rozšiřuje Object.The serialization architecture handles object types that extend MarshalByRefObject the same as types that extend Object. Tyto typy lze označit pomocí SerializableAttribute a implementovat rozhraní ISerializable jako jakýkoli jiný typ objektu.These types can be marked with the SerializableAttribute and implement the ISerializable interface as any other object type. Stav objektu bude zachycen a uložen do datového proudu.Their object state will be captured and persisted onto the stream.

Když se tyto typy používají prostřednictvím System.Runtime.Remoting, poskytuje infrastruktura pro vzdálenou komunikaci, která zachází z typické serializace a místo toho pro MarshalByRefObjectserializace proxy serveru.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. Náhradní je pomocná osoba, která ví, jak serializovat a deserializovat objekty určitého typu.A surrogate is a helper that knows how to serialize and deserialize objects of a particular type. Proxy server, který je pro uživatele neviditelný, ve většině případů bude typu ObjRef.The proxy, invisible to the user in most cases, will be of type ObjRef.

Jako obecný vzor návrhu by byla neobvyklá třída, aby byla označena atributem serializovatelný a rozšířila MarshalByRefObject.As a general design pattern, it would be unusual for a class to be both marked with the serializable attribute and extend MarshalByRefObject. Vývojáři by se měli pečlivě domnívat o možných scénářích serializace a vzdálené komunikace při kombinaci těchto dvou vlastností.Developers should think carefully about the possible serialization and remoting scenarios when combining these two characteristics. Jeden příklad, kde může být možné použít, je MemoryStream.One example where this might be applicable is with a MemoryStream. I když základní třída MemoryStream (Stream) sahá z MarshalByRefObject, je možné zachytit stav MemoryStream a obnovit ho v.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. Proto může být smysluplné serializovat stav tohoto streamu do databáze a později ho obnovit.It might, therefore, be meaningful to serialize the state of this stream into a database and restore it at some later point in time. Nicméně při použití prostřednictvím vzdálené komunikace by byl objekt tohoto typu proxy.However, when used through remoting, an object of this type would be proxied.

Další informace o serializaci tříd, které přesahují MarshalByRefObject, naleznete v tématu RemotingSurrogateSelector.For more information about serialization of classes that extend MarshalByRefObject, see RemotingSurrogateSelector. Další informace o implementaci ISerializablenaleznete v tématu Custom Serialization.For more information about implementing ISerializable, see Custom Serialization.

Poznámky pro implementátory

Implementací tohoto rozhraní umožníte, aby se objekt účastnil jeho vlastní serializace a deserializace.Implement this interface to allow an object to take part in its own serialization and deserialization.

Metody

GetObjectData(SerializationInfo, StreamingContext)

Naplní SerializationInfo daty potřebnými k serializaci cílového objektu.Populates a SerializationInfo with the data needed to serialize the target object.

Platí pro

Viz také