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

備註

SoapFormatter和類別BinaryFormatterIFormatter執行IRemotingFormatter 介面IRemotingFormatter, 以支援遠端程序呼叫 (rpc) 和介面 (由繼承), 以支持對象圖形的序列化。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. 類別也ISoapMessage 支援IRemotingFormatter物件的 rpc, 而不使用功能。 SoapFormatterThe 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).

使用獨立于兩BinaryFormatter個不同部分的 rpc: 方法呼叫, 其會使用包含所呼叫之方法的遠端物件傳送至伺服器, 以及從伺服器傳送到具有狀態和回應之用戶端的方法回應來自所呼叫方法的資訊。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. 當叫用委派時, 它會以所呼叫的方法傳回遠端物件的 URI。 HeaderHandler BinaryFormatterWhen 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. 這些詳細資料會改為從原始方法呼叫取得, 而這會傳遞DeserializeMethodResponseIMethodCallMessage參數中的方法。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.

不成對的代理Unpaired Surrogates

任何不成對的代理字元都會在二進位序列化中遺失。Any unpaired surrogate characters are lost in binary serialization. 例如, 下列字串包含一個高代理 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

還原序列化之後, 會遺失高代理 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.

適用於