BinaryFormatter 类

定义

以二进制格式序列化和反序列化对象或连接对象的整个图形。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
继承
BinaryFormatter
属性
实现

示例

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

注解

IFormatter IRemotingFormatter和类实现接口IRemotingFormatter以支持远程过程调用 (rpc) 和接口 (由继承) 以支持对象图形的序列化。 BinaryFormatter SoapFormatterThe 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 rpc, 无需使用IRemotingFormatter此功能。 SoapFormatterThe SoapFormatter class also supports RPCs with ISoapMessage objects, without using the IRemotingFormatter functionality.

在 rpc 过程中IRemotingFormatter , 接口允许指定两个单独的对象图: 要序列化的对象的图形, 以及包含一个标头对象数组的附加关系图, 该数组传递有关远程函数调用的信息 (对于例如, transaction ID 或方法签名)。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. BinaryFormatterHeaderHandler调用委托时, 它将返回远程对象的 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. 这些详细信息是从原始方法调用获取的, 该方法调用将传递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. 例如, 下面的字符串在两个(\ud800 Test单词之间包含一个高代理项 Unicode 字符):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 类的新实例。Initializes a new instance of the BinaryFormatter class with default values.

BinaryFormatter(ISurrogateSelector, StreamingContext)

使用给定的代理项选择器和流上下文来初始化 BinaryFormatter 类的新实例。Initializes a new instance of the BinaryFormatter class with a given surrogate selector and streaming context.

属性

AssemblyFormat

获取或设置与查找加集有关的反序列化器行为。Gets or sets the behavior of the deserializer with regards to finding and loading assemblies.

Binder

获取或设置控制将序列化对象绑定到类型的 SerializationBinder 类型的对象。Gets or sets an object of type SerializationBinder that controls the binding of a serialized object to a type.

Context

获取或设置此格式化程序的 StreamingContextGets or sets the StreamingContext for this formatter.

FilterLevel

获取或设置 TypeFilterLevel 所执行的自动反序列化的 BinaryFormatterGets or sets the TypeFilterLevel of automatic deserialization the BinaryFormatter performs.

SurrogateSelector

获取或设置控制序列化和反序列化过程的类型替换的 ISurrogateSelector.Gets or sets a ISurrogateSelector that controls type substitution during serialization and deserialization.

TypeFormat

获取或设置类型说明在序列化流中的布局格式。Gets or sets the format in which type descriptions are laid out in the serialized stream.

方法

Deserialize(Stream)

将指定的流反序列化为对象图形。Deserializes the specified stream into an object graph.

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)

将对远程方法调用的响应从所提供的 Stream 进行反序列化。Deserializes a response to a remote method call from the provided Stream.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
Serialize(Stream, Object)

将对象或具有指定顶级(根)的对象图形序列化为给定流。Serializes the object, or graph of objects with the specified top (root), to the given stream.

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()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)
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)

将对远程方法调用的响应从所提供的 Stream 进行反序列化。Deserializes a response to a remote method call from the provided Stream.

适用于