BinaryFormatter BinaryFormatter BinaryFormatter BinaryFormatter Class

定義

以二進位格式將物件或連接物件的整個圖形序列化和還原序列化。Serializes and deserializes an object, or an entire graph of connected objects, in binary format.

public ref class BinaryFormatter sealed : System::Runtime::Remoting::Messaging::IRemotingFormatter
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class BinaryFormatter : System.Runtime.Remoting.Messaging.IRemotingFormatter
type BinaryFormatter = class
    interface IRemotingFormatter
    interface IFormatter
Public NotInheritable Class BinaryFormatter
Implements IRemotingFormatter
繼承
BinaryFormatterBinaryFormatterBinaryFormatterBinaryFormatter
屬性
實作

範例

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 App
{
public:
   static void Serialize()
   {
      
      // Create a hashtable of values that will eventually be serialized.
      Hashtable^ addresses = gcnew Hashtable;
      addresses->Add( "Jeff", "123 Main Street, Redmond, WA 98052" );
      addresses->Add( "Fred", "987 Pine Road, Phila., PA 19116" );
      addresses->Add( "Mary", "PO Box 112233, Palo Alto, CA 94301" );
      
      // To serialize the hashtable (and its keys/values),  
      // you must first open a stream for writing. 
      // In this case we will use a file stream.
      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;
      try
      {
         formatter->Serialize( fs, addresses );
      }
      catch ( SerializationException^ e ) 
      {
         Console::WriteLine( "Failed to serialize. Reason: {0}", e->Message );
         throw;
      }
      finally
      {
         fs->Close();
      }

   }

   static void Deserialize()
   {
      
      // Declare the hashtable reference.
      Hashtable^ addresses = nullptr;
      
      // Open the file containing the data that we want to deserialize.
      FileStream^ fs = gcnew FileStream( "DataFile.dat",FileMode::Open );
      try
      {
         BinaryFormatter^ formatter = gcnew BinaryFormatter;
         
         // Deserialize the hashtable from the file and 
         // assign the reference to our local variable.
         addresses = dynamic_cast<Hashtable^>(formatter->Deserialize( fs ));
      }
      catch ( SerializationException^ e ) 
      {
         Console::WriteLine( "Failed to deserialize. Reason: {0}", e->Message );
         throw;
      }
      finally
      {
         fs->Close();
      }

      
      // To prove that the table deserialized correctly, display the keys/values.
      IEnumerator^ myEnum = addresses->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         DictionaryEntry ^ de = safe_cast<DictionaryEntry ^>(myEnum->Current);
         Console::WriteLine( " {0} lives at {1}.", de->Key, de->Value );
      }
   }

};


[STAThread]
int main()
{
   App::Serialize();
   App::Deserialize();
   return 0;
}

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

public class App 
{
    [STAThread]
    static void Main() 
    {
        Serialize();
        Deserialize();
    }

    static void Serialize() 
    {
        // Create a hashtable of values that will eventually be serialized.
        Hashtable addresses = new Hashtable();
        addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052");
        addresses.Add("Fred", "987 Pine Road, Phila., PA 19116");
        addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301");

        // To serialize the hashtable and its key/value pairs,  
        // you must first open a stream for writing. 
        // In this case, use a file stream.
        FileStream fs = new FileStream("DataFile.dat", FileMode.Create);

        // Construct a BinaryFormatter and use it to serialize the data to the stream.
        BinaryFormatter formatter = new BinaryFormatter();
        try 
        {
            formatter.Serialize(fs, addresses);
        }
        catch (SerializationException e) 
        {
            Console.WriteLine("Failed to serialize. Reason: " + e.Message);
            throw;
        }
        finally 
        {
            fs.Close();
        }
    }

   
    static void Deserialize() 
    {
        // Declare the hashtable reference.
        Hashtable addresses  = null;

        // Open the file containing the data that you want to deserialize.
        FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
        try 
        {
            BinaryFormatter formatter = new BinaryFormatter();

            // Deserialize the hashtable from the file and 
            // assign the reference to the local variable.
            addresses = (Hashtable) formatter.Deserialize(fs);
        }
        catch (SerializationException e) 
        {
            Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
            throw;
        }
        finally 
        {
            fs.Close();
        }

        // To prove that the table deserialized correctly, 
        // display the key/value pairs.
        foreach (DictionaryEntry de in addresses) 
        {
            Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
        }
    }
}
Imports System.IO
Imports System.Collections
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization


Module App

    Sub Main()
        Serialize()
        Deserialize()
    End Sub

    Sub Serialize()

        ' Create a hashtable of values that will eventually be serialized.
        Dim addresses As New Hashtable
        addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052")
        addresses.Add("Fred", "987 Pine Road, Phila., PA 19116")
        addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301")

        ' To serialize the hashtable (and its key/value pairs),  
        ' you must first open a stream for writing. 
        ' In this case, use a file stream.
        Dim fs As New FileStream("DataFile.dat", FileMode.Create)

        ' Construct a BinaryFormatter and use it to serialize the data to the stream.
        Dim formatter As New BinaryFormatter
        Try
            formatter.Serialize(fs, addresses)
        Catch e As SerializationException
            Console.WriteLine("Failed to serialize. Reason: " & e.Message)
            Throw
        Finally
            fs.Close()
        End Try
    End Sub



    Sub Deserialize()
        ' Declare the hashtable reference.
        Dim addresses As Hashtable = Nothing

        ' Open the file containing the data that you want to deserialize.
        Dim fs As New FileStream("DataFile.dat", FileMode.Open)
        Try
            Dim formatter As New BinaryFormatter

            ' Deserialize the hashtable from the file and 
            ' assign the reference to the local variable.
            addresses = DirectCast(formatter.Deserialize(fs), Hashtable)
        Catch e As SerializationException
            Console.WriteLine("Failed to deserialize. Reason: " & e.Message)
            Throw
        Finally
            fs.Close()
        End Try

        ' To prove that the table deserialized correctly, 
        ' display the key/value pairs.
        Dim de As DictionaryEntry
        For Each de In addresses
            Console.WriteLine("{0} lives at {1}.", de.Key, de.Value)
        Next
    End Sub
End Module

備註

SoapFormatterBinaryFormatter類別會實作IRemotingFormatter介面,以支援遠端程序呼叫 (Rpc),而IFormatter介面 (繼承IRemotingFormatter) 以支援物件圖形序列化。The SoapFormatter and BinaryFormatter classes implement the IRemotingFormatter interface to support remote procedure calls (RPCs), and the IFormatter interface (inherited by the IRemotingFormatter) to support serialization of a graph of objects. SoapFormatter類別也支援使用 RpcISoapMessage物件,而不需使用IRemotingFormatter功能。The SoapFormatter class also supports RPCs with ISoapMessage objects, without using the IRemotingFormatter functionality.

Rpc 期間IRemotingFormatter介面可讓兩個不同的物件圖形的規格: 要序列化的物件圖形,以及包含傳達 (適用於遠端函式呼叫的相關資訊的標頭物件的陣列的其他圖形例如,交易識別碼或方法簽章)。During RPCs, the IRemotingFormatter interface allows the specification of two separate object graphs: the graph of objects to serialize, and an additional graph that contains an array of header objects that convey information about the remote function call (for example, transaction ID or a method signature).

使用的 RpcBinaryFormatter分成兩個不同的部分: 方法呼叫,會傳送到伺服器與遠端物件,其中包含呼叫的方法,並從伺服器傳送至用戶端狀態的方法回應和回應從被呼叫的方法資訊。RPCs that use the BinaryFormatter separate into two distinct parts: method calls, which are sent to the server with the remote object that contains the method called, and method responses, which are sent from the server to the client with the status and response information from the called method.

物件圖形的第一個物件必須支援的方法呼叫的序列化期間IMethodCallMessage介面。During serialization of a method call the first object of the object graph must support the IMethodCallMessage interface. 若要還原序列化的方法呼叫,使用Deserialize方法使用HeaderHandler參數。To deserialize a method call, use the Deserialize method with the HeaderHandler parameter. 使用遠端基礎結構HeaderHandler委派產生支援的物件ISerializable介面。The remoting infrastructure uses the HeaderHandler delegate to produce an object that supports the ISerializable interface. BinaryFormatter叫用HeaderHandler委派,它會傳回遠端物件的 URI 所呼叫的方法。When the BinaryFormatter invokes the HeaderHandler delegate, it returns the URI of the remote object with the method that is being called. 在圖形中的第一個物件傳回支援IMethodCallMessage介面。The first object in the graph returned supports the IMethodCallMessage interface.

方法回應的序列化程序是相同的方法呼叫的除了第一個物件的物件圖形必須支援IMethodReturnMessage介面。The serialization procedure for a method response is identical to that of a method call, except the first object of the object graph must support the IMethodReturnMessage interface. 若要還原序列化方法回應,使用DeserializeMethodResponse方法。To deserialize a method response, use the DeserializeMethodResponse method. 為了節省時間,呼叫端物件的相關詳細資料會不傳送至遠端物件方法呼叫期間。To save time, details about the caller object are not sent to the remote object during the method call. 從原始的方法呼叫會傳遞至改為取得這些詳細資料DeserializeMethodResponse方法中的IMethodCallMessage參數。These details are instead obtained from the original method call, which is passed to the DeserializeMethodResponse method in the IMethodCallMessage parameter. 傳回圖形中的第一個物件DeserializeMethodResponse方法可支援IMethodReturnMessage介面。The first object in the graph returned by the DeserializeMethodResponse method supports the IMethodReturnMessage interface.

重要

將不受信任的資料還原序列化使用二進位序列化可能會導致安全性風險。Using binary serialization to deserialize untrusted data can lead to security risks. 如需詳細資訊,請參閱資料驗證For more information, see Data Validation.

非成對的 SurrogatesUnpaired Surrogates

二進位序列化中不會遺失任何未配對的 surrogate 字元。Any unpaired surrogate characters are lost in binary serialization. 例如,下列字串會包含高 surrogate 的 Unicode 字元(\ud800) 之間兩個Test單字:For example, the following string contains a high surrogate Unicode character (\ud800) in between the two Test words:

Test\ud800Test

序列化之前的位元組陣列的字串如下所示:Before serialization, the byte array of the string is as follows:

位元組陣列值Byte Array Value 字元Character
8484 TT
101101 ee
115115 s
116116 tt
5529655296 \ud800\ud800
8484 TT
101101 ee
115115 s
116116 tt

之後還原序列化時,高 surrogate 的 Unicode 字元則會遺失項目:After deserialization, the high surrogate Unicode character is lost:

位元組陣列值Byte Array Value 字元Character
8484 TT
101101 ee
115115 s
116116 tt
8484 TT
101101 ee
115115 s
116116 tt

建構函式

BinaryFormatter() BinaryFormatter() BinaryFormatter() BinaryFormatter()

使用預設值,初始化 BinaryFormatter 類別的新執行個體。Initializes a new instance of the BinaryFormatter class with default values.

BinaryFormatter(ISurrogateSelector, StreamingContext) BinaryFormatter(ISurrogateSelector, StreamingContext) BinaryFormatter(ISurrogateSelector, StreamingContext) BinaryFormatter(ISurrogateSelector, StreamingContext)

使用指定的代理選取器和資料流內容,初始化 BinaryFormatter 類別的新執行個體。Initializes a new instance of the BinaryFormatter class with a given surrogate selector and streaming context.

屬性

AssemblyFormat AssemblyFormat AssemblyFormat AssemblyFormat

取得或設定有關尋找和載入組件之還原序列化程式的行為。Gets or sets the behavior of the deserializer with regards to finding and loading assemblies.

Binder Binder Binder Binder

取得或設定控制將序列化物件繫結至型別的 SerializationBinder 型別物件。Gets or sets an object of type SerializationBinder that controls the binding of a serialized object to a type.

Context Context Context Context

取得或設定這個格式子的 StreamingContextGets or sets the StreamingContext for this formatter.

FilterLevel FilterLevel FilterLevel FilterLevel

取得或設定 TypeFilterLevel 所執行自動還原序列化的 BinaryFormatterGets or sets the TypeFilterLevel of automatic deserialization the BinaryFormatter performs.

SurrogateSelector SurrogateSelector SurrogateSelector SurrogateSelector

取得或設定 ISurrogateSelector,其控制序列化和還原序列化期間的型別替代。Gets or sets a ISurrogateSelector that controls type substitution during serialization and deserialization.

TypeFormat TypeFormat TypeFormat TypeFormat

取得或設定型別描述在已序列化資料流中的配置格式。Gets or sets the format in which type descriptions are laid out in the serialized stream.

方法

Deserialize(Stream) Deserialize(Stream) Deserialize(Stream) Deserialize(Stream)

將指定的資料流還原序列化至物件圖形。Deserializes the specified stream into an object graph.

Deserialize(Stream, HeaderHandler) Deserialize(Stream, HeaderHandler) Deserialize(Stream, HeaderHandler) Deserialize(Stream, HeaderHandler)

將指定的資料流還原序列化至物件圖形。Deserializes the specified stream into an object graph. 所提供的 HeaderHandler 會處理該資料流中的任何標頭。The provided HeaderHandler handles any headers in that stream.

DeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) DeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) DeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) DeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage)

將回應還原序列化至來自所提供 Stream 的遠端方法呼叫。Deserializes a response to a remote method call from the provided Stream.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
Serialize(Stream, Object) Serialize(Stream, Object) Serialize(Stream, Object) Serialize(Stream, Object)

使用指定的最上層 (根),將物件或物件的圖形序列化至指定的資料流。Serializes the object, or graph of objects with the specified top (root), to the given stream.

Serialize(Stream, Object, Header[]) Serialize(Stream, Object, Header[]) Serialize(Stream, Object, Header[]) Serialize(Stream, Object, Header[])

使用指定的最上層 (根),將物件或物件的圖形序列化至附加所提供標頭的指定資料流。Serializes the object, or graph of objects with the specified top (root), to the given stream attaching the provided headers.

ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)
UnsafeDeserialize(Stream, HeaderHandler) UnsafeDeserialize(Stream, HeaderHandler) UnsafeDeserialize(Stream, HeaderHandler) UnsafeDeserialize(Stream, HeaderHandler)

將指定的資料流還原序列化至物件圖形。Deserializes the specified stream into an object graph. 所提供的 HeaderHandler 會處理該資料流中的任何標頭。The provided HeaderHandler handles any headers in that stream.

UnsafeDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) UnsafeDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) UnsafeDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) UnsafeDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage)

將回應還原序列化至來自所提供 Stream 的遠端方法呼叫。Deserializes a response to a remote method call from the provided Stream.

適用於