ISerializable 介面

定義

允許物件控制它自己的序列化 (Serialization) 和還原序列化 (Deserialization)。

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
衍生
屬性

範例

下列程式碼範例示範如何使用 ISerializable 介面來定義類別的自訂序列化行為。

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

備註

任何可能序列化的類別都必須以 SerializableAttribute 標示。 如果類別需要控制其序列化程式,它可以實作 ISerializable 介面。 會在 Formatter 序列化時間呼叫 GetObjectData ,並填入提供 SerializationInfo 的所有資料來表示物件。 會 FormatterSerializationInfo 圖形中的 物件型別建立 。 需要自行傳送 Proxy 的物件可以使用 FullTypeNameAssemblyName 方法來 SerializationInfo 變更傳輸的資訊。

在類別繼承的情況下,可以序列化衍生自實作 的基類的 ISerializable 類別。 在此情況下,衍生類別應該在其 的 實作內呼叫 的 GetObjectData 基類實作 GetObjectData 。 否則,將不會序列化基類中的資料。

介面 ISerializable 表示具有簽章 的建構函式 constructor (SerializationInfo information, StreamingContext context) 。 在還原序列化時,只有在 格式子還原序列化 中的 SerializationInfo 資料之後,才會呼叫目前的建構函式。 一般而言,如果 類別不是 sealed ,則此建構函式應該是 protected

無法保證還原序列化物件的順序。 例如,如果某個類型參考尚未還原序列化的型別,就會發生例外狀況。 如果您要建立具有這類相依性的型別,您可以實 IDeserializationCallback 作 介面和 OnDeserialization 方法來解決問題。

序列化架構會處理與擴充 MarshalByRefObject Object 之類型相同的物件類型。 這些型別可以使用 標記 SerializableAttribute ,並實作 ISerializable 介面做為任何其他物件類型。 其物件狀態會擷取並保存在資料流程上。

透過 使用這些 System.Runtime.Remoting 型別時,遠端基礎結構會提供代理,其會優先處理一般序列化,並改為將 Proxy 序列化至 MarshalByRefObject 。 Surrogate 是協助程式,知道如何序列化和還原序列化特定類型的物件。 在大部分情況下,使用者看不到 Proxy 的類型為 ObjRef

做為一般設計模式,類別會以可序列化屬性標示並延伸 MarshalByRefObject 。 開發人員在結合這兩個特性時,應該仔細考慮可能的序列化和遠端案例。 其中一個可能適用的範例是 使用 MemoryStream 。 雖然 (StreamMemoryStream 基類) 從 MarshalByRefObject 延伸,但可以擷取 的狀態 MemoryStream ,並依序還原狀態。 因此,將這個資料流程的狀態序列化為資料庫,並在稍後的時間點還原它可能有意義。 不過,透過遠端處理使用時,此類型的物件會進行 Proxy 處理。

如需擴充 MarshalByRefObject 之類別序列化的詳細資訊,請參閱 RemotingSurrogateSelector 。 如需實作 ISerializable 的詳細資訊,請參閱 自訂序列化

給實施者的注意事項

實作這個介面,讓物件參與其本身的序列化和還原序列化。

方法

GetObjectData(SerializationInfo, StreamingContext)

將序列化目標物件所需的資料填入 SerializationInfo

適用於

另請參閱